@objectstack/client 4.0.3 → 4.0.5

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.js CHANGED
@@ -24,12 +24,13 @@ __export(index_exports, {
24
24
  ObjectStackClient: () => ObjectStackClient,
25
25
  QueryBuilder: () => QueryBuilder,
26
26
  RealtimeAPI: () => RealtimeAPI,
27
+ ScopedProjectClient: () => ScopedProjectClient,
27
28
  createFilter: () => createFilter,
28
29
  createQuery: () => createQuery
29
30
  });
30
31
  module.exports = __toCommonJS(index_exports);
31
32
  var import_data = require("@objectstack/spec/data");
32
- var import_core = require("@objectstack/core");
33
+ var import_logger = require("@objectstack/core/logger");
33
34
 
34
35
  // src/realtime-api.ts
35
36
  var RealtimeAPI = class {
@@ -660,10 +661,637 @@ var ObjectStackClient = class {
660
661
  return this.unwrapResponse(res);
661
662
  }
662
663
  };
664
+ /**
665
+ * Environment Management Services
666
+ *
667
+ * Environments are the v4.1+ isolation primitive — each project owns a
668
+ * physically separate data-plane database. All Studio-level switching goes
669
+ * through this API.
670
+ *
671
+ * Endpoints:
672
+ * - GET /api/v1/cloud/projects → list environments
673
+ * - GET /api/v1/cloud/projects/:id → get one (with database info)
674
+ * - POST /api/v1/cloud/projects → provision a new project
675
+ * - PATCH /api/v1/cloud/projects/:id → update (displayName, plan, status, …)
676
+ * - POST /api/v1/cloud/projects/:id/activate → set as session's active project
677
+ * - POST /api/v1/cloud/projects/:id/credentials/rotate → rotate credential
678
+ *
679
+ * @see docs/adr/0002-project-database-isolation.md
680
+ */
681
+ this.projects = {
682
+ /**
683
+ * List environments visible to the current session. Optionally filter
684
+ * by organization (control-plane query — not routed through a data-plane DB).
685
+ */
686
+ list: async (filters) => {
687
+ const params = new URLSearchParams();
688
+ if (filters?.organization_id) params.set("organizationId", filters.organization_id);
689
+ if (filters?.env_type) params.set("envType", filters.env_type);
690
+ if (filters?.status) params.set("status", filters.status);
691
+ const qs = params.toString();
692
+ const url = `${this.baseUrl}/api/v1/cloud/projects${qs ? "?" + qs : ""}`;
693
+ const res = await this.fetch(url);
694
+ return this.unwrapResponse(res);
695
+ },
696
+ /**
697
+ * Get a single project (joined with its database and membership row).
698
+ */
699
+ get: async (id) => {
700
+ const res = await this.fetch(`${this.baseUrl}/api/v1/cloud/projects/${encodeURIComponent(id)}`);
701
+ return this.unwrapResponse(res);
702
+ },
703
+ /**
704
+ * Provision a new project. Delegates to
705
+ * `ProjectProvisioningService.provisionProject` on the server.
706
+ */
707
+ create: async (req) => {
708
+ const res = await this.fetch(`${this.baseUrl}/api/v1/cloud/projects`, {
709
+ method: "POST",
710
+ body: JSON.stringify(req)
711
+ });
712
+ return this.unwrapResponse(res);
713
+ },
714
+ /**
715
+ * Update a project (display_name, plan, status, is_default, metadata).
716
+ */
717
+ update: async (id, patch) => {
718
+ const res = await this.fetch(`${this.baseUrl}/api/v1/cloud/projects/${encodeURIComponent(id)}`, {
719
+ method: "PATCH",
720
+ body: JSON.stringify(patch)
721
+ });
722
+ return this.unwrapResponse(res);
723
+ },
724
+ /**
725
+ * Cascade-delete a project: cleans up credential/member/package_installation
726
+ * rows, releases the physical database via the provisioning adapter, and
727
+ * removes the `sys_project` row. Default projects require `force: true`.
728
+ */
729
+ delete: async (id, opts) => {
730
+ const qs = opts?.force ? "?force=1" : "";
731
+ const res = await this.fetch(
732
+ `${this.baseUrl}/api/v1/cloud/projects/${encodeURIComponent(id)}${qs}`,
733
+ { method: "DELETE" }
734
+ );
735
+ return this.unwrapResponse(res);
736
+ },
737
+ /**
738
+ * Activate this project for the current session. The server writes
739
+ * `active_environment_id` on the better-auth session; subsequent requests
740
+ * are routed to this project's database.
741
+ */
742
+ activate: async (id) => {
743
+ const res = await this.fetch(`${this.baseUrl}/api/v1/cloud/projects/${encodeURIComponent(id)}/activate`, {
744
+ method: "POST"
745
+ });
746
+ return this.unwrapResponse(res);
747
+ },
748
+ /**
749
+ * Rotate the active database credential for this project.
750
+ */
751
+ rotateCredential: async (id, plaintext) => {
752
+ const res = await this.fetch(`${this.baseUrl}/api/v1/cloud/projects/${encodeURIComponent(id)}/credentials/rotate`, {
753
+ method: "POST",
754
+ body: JSON.stringify({ plaintext })
755
+ });
756
+ return this.unwrapResponse(res);
757
+ },
758
+ /**
759
+ * Update the hostname bound to this project. Validates format and
760
+ * uniqueness server-side; invalidates the dispatcher's routing cache.
761
+ */
762
+ updateHostname: async (id, hostname) => {
763
+ const res = await this.fetch(`${this.baseUrl}/api/v1/cloud/projects/${encodeURIComponent(id)}/hostname`, {
764
+ method: "POST",
765
+ body: JSON.stringify({ hostname })
766
+ });
767
+ return this.unwrapResponse(res);
768
+ },
769
+ /**
770
+ * Retry provisioning for a project stuck in `failed` (or
771
+ * `provisioning`) state. The server re-runs the driver handshake; on
772
+ * success the project flips to `active`, on failure it stays
773
+ * `failed` with `metadata.provisioningError` updated.
774
+ */
775
+ retryProvisioning: async (id) => {
776
+ const res = await this.fetch(`${this.baseUrl}/api/v1/cloud/projects/${encodeURIComponent(id)}/retry`, {
777
+ method: "POST"
778
+ });
779
+ return this.unwrapResponse(res);
780
+ },
781
+ /**
782
+ * List members of a project (per-project RBAC).
783
+ */
784
+ listMembers: async (id) => {
785
+ const res = await this.fetch(`${this.baseUrl}/api/v1/cloud/projects/${encodeURIComponent(id)}/members`);
786
+ return this.unwrapResponse(res);
787
+ },
788
+ /**
789
+ * List ObjectQL drivers registered on the server. Useful for populating a
790
+ * driver selector when provisioning a new project (memory / turso /
791
+ * future sql drivers). Returned `name` is the short alias (e.g. `memory`,
792
+ * `turso`); `driverId` is the full FQN (e.g. `com.objectstack.driver.memory`).
793
+ */
794
+ listDrivers: async () => {
795
+ const res = await this.fetch(`${this.baseUrl}/api/v1/cloud/drivers`);
796
+ return this.unwrapResponse(res);
797
+ },
798
+ /**
799
+ * List available project templates. Templates are seeded into the project
800
+ * database once at provisioning time when `template_id` is supplied.
801
+ */
802
+ listTemplates: async () => {
803
+ const res = await this.fetch(`${this.baseUrl}/api/v1/cloud/templates`);
804
+ return this.unwrapResponse(res);
805
+ },
806
+ /**
807
+ * Per-project package installation management (Power Apps "solution" model).
808
+ * Install records are stored in the environment's own database.
809
+ */
810
+ packages: {
811
+ /** List all packages installed in a specific project. */
812
+ list: async (envId) => {
813
+ const res = await this.fetch(`${this.baseUrl}/api/v1/cloud/projects/${encodeURIComponent(envId)}/packages`);
814
+ return this.unwrapResponse(res);
815
+ },
816
+ /** Install a package into the project. */
817
+ install: async (envId, body) => {
818
+ const res = await this.fetch(`${this.baseUrl}/api/v1/cloud/projects/${encodeURIComponent(envId)}/packages`, {
819
+ method: "POST",
820
+ body: JSON.stringify(body)
821
+ });
822
+ return this.unwrapResponse(res);
823
+ },
824
+ /** Get a single installation record. */
825
+ get: async (envId, pkgId) => {
826
+ const res = await this.fetch(`${this.baseUrl}/api/v1/cloud/projects/${encodeURIComponent(envId)}/packages/${encodeURIComponent(pkgId)}`);
827
+ return this.unwrapResponse(res);
828
+ },
829
+ /** Enable a previously disabled package. */
830
+ enable: async (envId, pkgId) => {
831
+ const res = await this.fetch(`${this.baseUrl}/api/v1/cloud/projects/${encodeURIComponent(envId)}/packages/${encodeURIComponent(pkgId)}/enable`, {
832
+ method: "PATCH"
833
+ });
834
+ return this.unwrapResponse(res);
835
+ },
836
+ /** Disable an installed package (metadata will not be loaded). */
837
+ disable: async (envId, pkgId) => {
838
+ const res = await this.fetch(`${this.baseUrl}/api/v1/cloud/projects/${encodeURIComponent(envId)}/packages/${encodeURIComponent(pkgId)}/disable`, {
839
+ method: "PATCH"
840
+ });
841
+ return this.unwrapResponse(res);
842
+ },
843
+ /** Uninstall a package from the project. Forbidden for scope=platform packages. */
844
+ uninstall: async (envId, pkgId) => {
845
+ const res = await this.fetch(`${this.baseUrl}/api/v1/cloud/projects/${encodeURIComponent(envId)}/packages/${encodeURIComponent(pkgId)}`, {
846
+ method: "DELETE"
847
+ });
848
+ return this.unwrapResponse(res);
849
+ },
850
+ /** Upgrade an installed package to a newer version. */
851
+ upgrade: async (envId, pkgId, targetVersion) => {
852
+ const res = await this.fetch(`${this.baseUrl}/api/v1/cloud/projects/${encodeURIComponent(envId)}/packages/${encodeURIComponent(pkgId)}/upgrade`, {
853
+ method: "POST",
854
+ body: JSON.stringify({ targetVersion })
855
+ });
856
+ return this.unwrapResponse(res);
857
+ }
858
+ }
859
+ };
860
+ /**
861
+ * Organization Services
862
+ *
863
+ * Thin wrapper around better-auth's organization plugin endpoints, which
864
+ * are mounted under `/api/v1/auth/organization/**`. Used by the Studio
865
+ * OrganizationSwitcher and the /orgs management routes.
866
+ */
867
+ this.organizations = {
868
+ /**
869
+ * List organizations the current user belongs to.
870
+ * GET /api/v1/auth/organization/list
871
+ */
872
+ list: async () => {
873
+ const route = this.getRoute("auth");
874
+ const res = await this.fetch(`${this.baseUrl}${route}/organization/list`);
875
+ const data = await res.json();
876
+ const orgs = Array.isArray(data) ? data : data?.data ?? [];
877
+ return { organizations: orgs };
878
+ },
879
+ /**
880
+ * Create a new organization.
881
+ * POST /api/v1/auth/organization/create
882
+ */
883
+ create: async (req) => {
884
+ const route = this.getRoute("auth");
885
+ const res = await this.fetch(`${this.baseUrl}${route}/organization/create`, {
886
+ method: "POST",
887
+ body: JSON.stringify(req)
888
+ });
889
+ return res.json();
890
+ },
891
+ /**
892
+ * Update an existing organization.
893
+ * POST /api/v1/auth/organization/update
894
+ *
895
+ * better-auth requires the caller to be an owner/admin (server-side
896
+ * enforcement); the body shape is `{ organizationId, data: {...} }`.
897
+ */
898
+ update: async (organizationId, data) => {
899
+ const route = this.getRoute("auth");
900
+ const res = await this.fetch(`${this.baseUrl}${route}/organization/update`, {
901
+ method: "POST",
902
+ body: JSON.stringify({ organizationId, data })
903
+ });
904
+ return res.json();
905
+ },
906
+ /**
907
+ * Set the active organization on the current session. The server writes
908
+ * `activeOrganizationId` on the better-auth session, which downstream
909
+ * handlers (e.g. `EnvironmentProvisioningService`) consult.
910
+ *
911
+ * POST /api/v1/auth/organization/set-active
912
+ */
913
+ setActive: async (organizationId) => {
914
+ const route = this.getRoute("auth");
915
+ const res = await this.fetch(`${this.baseUrl}${route}/organization/set-active`, {
916
+ method: "POST",
917
+ body: JSON.stringify({ organizationId })
918
+ });
919
+ return res.json();
920
+ },
921
+ /**
922
+ * Get full organization detail (members, invitations, teams).
923
+ * GET /api/v1/auth/organization/get-full-organization?organizationId=...
924
+ */
925
+ get: async (organizationId) => {
926
+ const route = this.getRoute("auth");
927
+ const res = await this.fetch(
928
+ `${this.baseUrl}${route}/organization/get-full-organization?organizationId=${encodeURIComponent(organizationId)}`
929
+ );
930
+ return res.json();
931
+ },
932
+ /**
933
+ * List members of an organization.
934
+ */
935
+ listMembers: async (organizationId) => {
936
+ const route = this.getRoute("auth");
937
+ const res = await this.fetch(
938
+ `${this.baseUrl}${route}/organization/list-members?organizationId=${encodeURIComponent(organizationId)}`
939
+ );
940
+ return res.json();
941
+ },
942
+ /**
943
+ * Invite a user to the organization.
944
+ */
945
+ invite: async (req) => {
946
+ const route = this.getRoute("auth");
947
+ const res = await this.fetch(`${this.baseUrl}${route}/organization/invite-member`, {
948
+ method: "POST",
949
+ body: JSON.stringify(req)
950
+ });
951
+ return res.json();
952
+ },
953
+ /**
954
+ * Leave the given organization.
955
+ */
956
+ leave: async (organizationId) => {
957
+ const route = this.getRoute("auth");
958
+ const res = await this.fetch(`${this.baseUrl}${route}/organization/leave`, {
959
+ method: "POST",
960
+ body: JSON.stringify({ organizationId })
961
+ });
962
+ return res.json();
963
+ },
964
+ /**
965
+ * Delete an organization via better-auth's organization plugin.
966
+ *
967
+ * POST /api/v1/auth/organization/delete
968
+ *
969
+ * better-auth removes the organization row, all members, and all
970
+ * pending invitations. Project teardown (per-project DBs, etc.) is
971
+ * handled server-side by hooks attached to the organization plugin.
972
+ */
973
+ delete: async (organizationId) => {
974
+ const route = this.getRoute("auth");
975
+ const res = await this.fetch(`${this.baseUrl}${route}/organization/delete`, {
976
+ method: "POST",
977
+ body: JSON.stringify({ organizationId })
978
+ });
979
+ return res.json();
980
+ },
981
+ /**
982
+ * Remove a member from an organization.
983
+ *
984
+ * better-auth: POST /organization/remove-member
985
+ * Body: `{ memberIdOrEmail, organizationId? }` — note the parameter is the
986
+ * **member id** (the row id from `member` table) or the user's email; it
987
+ * is *not* the bare `userId`. Server enforces owner/admin permission.
988
+ */
989
+ removeMember: async (organizationId, params) => {
990
+ const route = this.getRoute("auth");
991
+ const res = await this.fetch(`${this.baseUrl}${route}/organization/remove-member`, {
992
+ method: "POST",
993
+ body: JSON.stringify({ memberIdOrEmail: params.memberIdOrEmail, organizationId })
994
+ });
995
+ return res.json();
996
+ },
997
+ /**
998
+ * Change a member's role in an organization (owner/admin only).
999
+ *
1000
+ * better-auth: POST /organization/update-member-role
1001
+ * Body: `{ memberId, role, organizationId? }`. The `memberId` is the
1002
+ * `member` table row id (not user id). `role` is one of the configured
1003
+ * organisation roles (default: `owner | admin | member`).
1004
+ */
1005
+ updateMemberRole: async (organizationId, params) => {
1006
+ const route = this.getRoute("auth");
1007
+ const res = await this.fetch(`${this.baseUrl}${route}/organization/update-member-role`, {
1008
+ method: "POST",
1009
+ body: JSON.stringify({ memberId: params.memberId, role: params.role, organizationId })
1010
+ });
1011
+ return res.json();
1012
+ },
1013
+ /**
1014
+ * Look up the calling user's membership row in the given organisation.
1015
+ * Useful for permission checks on the client without having to scan the
1016
+ * full member list.
1017
+ *
1018
+ * better-auth: GET /organization/get-active-member?organizationId=…
1019
+ */
1020
+ getActiveMember: async (organizationId) => {
1021
+ const route = this.getRoute("auth");
1022
+ const res = await this.fetch(
1023
+ `${this.baseUrl}${route}/organization/get-active-member?organizationId=${encodeURIComponent(organizationId)}`
1024
+ );
1025
+ return res.json();
1026
+ },
1027
+ /**
1028
+ * Invitation lifecycle — wraps better-auth's organization-plugin
1029
+ * invitation endpoints. Always go through here instead of writing to
1030
+ * `sys_invitation` via the data API: the better-auth writers handle
1031
+ * status transitions, expiry, dedupe, and the `sendInvitationEmail`
1032
+ * side-effect that the auth-manager wires up.
1033
+ */
1034
+ invitations: {
1035
+ /**
1036
+ * List pending/accepted/canceled invitations for an organization.
1037
+ * Requires owner/admin role on that org.
1038
+ *
1039
+ * better-auth: GET /organization/list-invitations?organizationId=…
1040
+ */
1041
+ list: async (organizationId) => {
1042
+ const route = this.getRoute("auth");
1043
+ const res = await this.fetch(
1044
+ `${this.baseUrl}${route}/organization/list-invitations?organizationId=${encodeURIComponent(organizationId)}`
1045
+ );
1046
+ const data = await res.json();
1047
+ const invitations = Array.isArray(data) ? data : data?.data ?? data?.invitations ?? [];
1048
+ return { invitations };
1049
+ },
1050
+ /**
1051
+ * List the **current user's** incoming invitations across every
1052
+ * organisation. Used by the per-user "Invitations" inbox page.
1053
+ *
1054
+ * better-auth: GET /organization/list-user-invitations
1055
+ */
1056
+ listMine: async () => {
1057
+ const route = this.getRoute("auth");
1058
+ const res = await this.fetch(`${this.baseUrl}${route}/organization/list-user-invitations`);
1059
+ const data = await res.json();
1060
+ const invitations = Array.isArray(data) ? data : data?.data ?? data?.invitations ?? [];
1061
+ return { invitations };
1062
+ },
1063
+ /** better-auth: POST /organization/cancel-invitation */
1064
+ cancel: async (invitationId) => {
1065
+ const route = this.getRoute("auth");
1066
+ const res = await this.fetch(`${this.baseUrl}${route}/organization/cancel-invitation`, {
1067
+ method: "POST",
1068
+ body: JSON.stringify({ invitationId })
1069
+ });
1070
+ return res.json();
1071
+ },
1072
+ /** better-auth: POST /organization/accept-invitation */
1073
+ accept: async (invitationId) => {
1074
+ const route = this.getRoute("auth");
1075
+ const res = await this.fetch(`${this.baseUrl}${route}/organization/accept-invitation`, {
1076
+ method: "POST",
1077
+ body: JSON.stringify({ invitationId })
1078
+ });
1079
+ return res.json();
1080
+ },
1081
+ /** better-auth: POST /organization/reject-invitation */
1082
+ reject: async (invitationId) => {
1083
+ const route = this.getRoute("auth");
1084
+ const res = await this.fetch(`${this.baseUrl}${route}/organization/reject-invitation`, {
1085
+ method: "POST",
1086
+ body: JSON.stringify({ invitationId })
1087
+ });
1088
+ return res.json();
1089
+ },
1090
+ /**
1091
+ * "Resend" an invitation. better-auth has no first-class resend
1092
+ * endpoint, so we implement it as cancel-then-invite: cancel the old
1093
+ * row (so its status flips to `canceled` and audit hooks fire), then
1094
+ * issue a fresh invite. The new invite re-runs `sendInvitationEmail`
1095
+ * on the server, so the recipient gets a brand-new accept URL.
1096
+ *
1097
+ * If `cancel()` fails (e.g. invite already accepted) the error is
1098
+ * re-thrown without re-inviting.
1099
+ */
1100
+ resend: async (invitation) => {
1101
+ if (invitation.id) {
1102
+ try {
1103
+ await this.organizations.invitations.cancel(invitation.id);
1104
+ } catch {
1105
+ }
1106
+ }
1107
+ return this.organizations.invite({
1108
+ email: invitation.email,
1109
+ role: invitation.role ?? "member",
1110
+ organizationId: invitation.organizationId
1111
+ });
1112
+ }
1113
+ },
1114
+ /**
1115
+ * Team management — only available when the organisation plugin is
1116
+ * configured with `teams: { enabled: true }` on the server. Calls return
1117
+ * a 4xx if teams aren't enabled; UI should hide the section in that case.
1118
+ */
1119
+ teams: {
1120
+ /** better-auth: GET /organization/list-teams?organizationId=… */
1121
+ list: async (organizationId) => {
1122
+ const route = this.getRoute("auth");
1123
+ const res = await this.fetch(
1124
+ `${this.baseUrl}${route}/organization/list-teams?organizationId=${encodeURIComponent(organizationId)}`
1125
+ );
1126
+ const data = await res.json();
1127
+ const teams = Array.isArray(data) ? data : data?.data ?? data?.teams ?? [];
1128
+ return { teams };
1129
+ },
1130
+ /** better-auth: POST /organization/create-team */
1131
+ create: async (req) => {
1132
+ const route = this.getRoute("auth");
1133
+ const res = await this.fetch(`${this.baseUrl}${route}/organization/create-team`, {
1134
+ method: "POST",
1135
+ body: JSON.stringify(req)
1136
+ });
1137
+ return res.json();
1138
+ },
1139
+ /** better-auth: POST /organization/update-team */
1140
+ update: async (params) => {
1141
+ const route = this.getRoute("auth");
1142
+ const res = await this.fetch(`${this.baseUrl}${route}/organization/update-team`, {
1143
+ method: "POST",
1144
+ body: JSON.stringify(params)
1145
+ });
1146
+ return res.json();
1147
+ },
1148
+ /** better-auth: POST /organization/remove-team */
1149
+ delete: async (params) => {
1150
+ const route = this.getRoute("auth");
1151
+ const res = await this.fetch(`${this.baseUrl}${route}/organization/remove-team`, {
1152
+ method: "POST",
1153
+ body: JSON.stringify(params)
1154
+ });
1155
+ return res.json();
1156
+ },
1157
+ /** better-auth: GET /organization/list-team-members?teamId=… */
1158
+ listMembers: async (teamId) => {
1159
+ const route = this.getRoute("auth");
1160
+ const res = await this.fetch(
1161
+ `${this.baseUrl}${route}/organization/list-team-members?teamId=${encodeURIComponent(teamId)}`
1162
+ );
1163
+ const data = await res.json();
1164
+ const members = Array.isArray(data) ? data : data?.data ?? data?.members ?? [];
1165
+ return { members };
1166
+ },
1167
+ /** better-auth: POST /organization/add-team-member */
1168
+ addMember: async (params) => {
1169
+ const route = this.getRoute("auth");
1170
+ const res = await this.fetch(`${this.baseUrl}${route}/organization/add-team-member`, {
1171
+ method: "POST",
1172
+ body: JSON.stringify(params)
1173
+ });
1174
+ return res.json();
1175
+ },
1176
+ /** better-auth: POST /organization/remove-team-member */
1177
+ removeMember: async (params) => {
1178
+ const route = this.getRoute("auth");
1179
+ const res = await this.fetch(`${this.baseUrl}${route}/organization/remove-team-member`, {
1180
+ method: "POST",
1181
+ body: JSON.stringify(params)
1182
+ });
1183
+ return res.json();
1184
+ }
1185
+ }
1186
+ };
1187
+ /**
1188
+ * OAuth / OpenID Connect Provider — admin endpoints exposed by
1189
+ * `@better-auth/oauth-provider` (when enabled on the server). Lets users
1190
+ * register their own OAuth client applications, list them, and revoke them.
1191
+ *
1192
+ * All endpoints are mounted under the auth route, e.g. `/api/v1/auth/oauth2/*`.
1193
+ */
1194
+ this.oauth = {
1195
+ applications: {
1196
+ /**
1197
+ * Register a new OAuth client application.
1198
+ * POST /api/v1/auth/oauth2/create-client (authenticated)
1199
+ *
1200
+ * Returns the freshly-issued `client_id` and `client_secret`.
1201
+ * The secret is only returned at creation time — store it securely.
1202
+ */
1203
+ register: async (req) => {
1204
+ const route = this.getRoute("auth");
1205
+ const res = await this.fetch(`${this.baseUrl}${route}/oauth2/create-client`, {
1206
+ method: "POST",
1207
+ body: JSON.stringify(req)
1208
+ });
1209
+ return res.json();
1210
+ },
1211
+ /**
1212
+ * Get a single OAuth application by its `client_id`.
1213
+ * GET /api/v1/auth/oauth2/get-client?client_id=...
1214
+ */
1215
+ get: async (clientId) => {
1216
+ const route = this.getRoute("auth");
1217
+ const res = await this.fetch(
1218
+ `${this.baseUrl}${route}/oauth2/get-client?client_id=${encodeURIComponent(clientId)}`
1219
+ );
1220
+ return res.json();
1221
+ },
1222
+ /**
1223
+ * Get a single OAuth application's public fields (no auth required
1224
+ * once the user has signed in). Used by the consent screen.
1225
+ * GET /api/v1/auth/oauth2/public-client?client_id=...
1226
+ */
1227
+ getPublic: async (clientId) => {
1228
+ const route = this.getRoute("auth");
1229
+ const res = await this.fetch(
1230
+ `${this.baseUrl}${route}/oauth2/public-client?client_id=${encodeURIComponent(clientId)}`
1231
+ );
1232
+ return res.json();
1233
+ },
1234
+ /**
1235
+ * List OAuth applications visible to the current user.
1236
+ *
1237
+ * Uses `@better-auth/oauth-provider`'s `/oauth2/get-clients` endpoint
1238
+ * which returns clients owned by the current user (and their
1239
+ * organization, if applicable).
1240
+ */
1241
+ list: async () => {
1242
+ const route = this.getRoute("auth");
1243
+ const res = await this.fetch(`${this.baseUrl}${route}/oauth2/get-clients`);
1244
+ const data = await res.json();
1245
+ const items = Array.isArray(data) ? data : data?.clients ?? data?.data ?? [];
1246
+ return { applications: items };
1247
+ },
1248
+ /**
1249
+ * Delete an OAuth application by its `client_id`.
1250
+ * POST /api/v1/auth/oauth2/delete-client
1251
+ *
1252
+ * Tokens and consents referencing the client cascade-delete via the
1253
+ * better-auth schema's `onDelete: cascade` foreign keys.
1254
+ */
1255
+ delete: async (clientId) => {
1256
+ const route = this.getRoute("auth");
1257
+ const res = await this.fetch(`${this.baseUrl}${route}/oauth2/delete-client`, {
1258
+ method: "POST",
1259
+ body: JSON.stringify({ client_id: clientId })
1260
+ });
1261
+ return res.json();
1262
+ }
1263
+ },
1264
+ /**
1265
+ * Submit the user's decision to a pending consent request.
1266
+ * POST /api/v1/auth/oauth2/consent
1267
+ *
1268
+ * Called by the consent screen after the user accepts or denies. The
1269
+ * `oauth_query` is the raw query string of the consent page URL — it
1270
+ * carries the signed authorization request that the consent endpoint
1271
+ * verifies before issuing the authorization code.
1272
+ */
1273
+ consent: async (req) => {
1274
+ const route = this.getRoute("auth");
1275
+ const res = await this.fetch(`${this.baseUrl}${route}/oauth2/consent`, {
1276
+ method: "POST",
1277
+ body: JSON.stringify(req)
1278
+ });
1279
+ return res.json();
1280
+ }
1281
+ };
663
1282
  /**
664
1283
  * Authentication Services
665
1284
  */
666
1285
  this.auth = {
1286
+ /**
1287
+ * Get authentication configuration
1288
+ * Returns available auth providers and features
1289
+ */
1290
+ getConfig: async () => {
1291
+ const route = this.getRoute("auth");
1292
+ const res = await this.fetch(`${this.baseUrl}${route}/config`);
1293
+ return this.unwrapResponse(res);
1294
+ },
667
1295
  /**
668
1296
  * Login with email and password
669
1297
  * Uses better-auth endpoint: POST /sign-in/email
@@ -672,8 +1300,100 @@ var ObjectStackClient = class {
672
1300
  const route = this.getRoute("auth");
673
1301
  const res = await this.fetch(`${this.baseUrl}${route}/sign-in/email`, {
674
1302
  method: "POST",
1303
+ headers: { Origin: this.baseUrl },
675
1304
  body: JSON.stringify(request)
676
1305
  });
1306
+ const raw = await res.json();
1307
+ const data = raw && (raw.data ?? (raw.token || raw.user ? { token: raw.token, user: raw.user } : void 0));
1308
+ const normalized = data ? { ...raw, data } : raw;
1309
+ if (normalized.data?.token) {
1310
+ this.token = normalized.data.token;
1311
+ }
1312
+ return normalized;
1313
+ },
1314
+ /**
1315
+ * Logout current user
1316
+ * Uses better-auth endpoint: POST /sign-out
1317
+ */
1318
+ logout: async () => {
1319
+ const route = this.getRoute("auth");
1320
+ await this.fetch(`${this.baseUrl}${route}/sign-out`, {
1321
+ method: "POST",
1322
+ headers: { "Content-Type": "application/json", Origin: this.baseUrl },
1323
+ body: "{}"
1324
+ });
1325
+ this.token = void 0;
1326
+ },
1327
+ /**
1328
+ * Get current user session
1329
+ * Uses better-auth endpoint: GET /get-session
1330
+ */
1331
+ me: async () => {
1332
+ const route = this.getRoute("auth");
1333
+ const res = await this.fetch(`${this.baseUrl}${route}/get-session`, {
1334
+ headers: { Origin: this.baseUrl }
1335
+ });
1336
+ return res.json();
1337
+ },
1338
+ /**
1339
+ * Register a new user account
1340
+ * Uses better-auth endpoint: POST /sign-up/email
1341
+ */
1342
+ register: async (request) => {
1343
+ const route = this.getRoute("auth");
1344
+ const res = await this.fetch(`${this.baseUrl}${route}/sign-up/email`, {
1345
+ method: "POST",
1346
+ headers: { Origin: this.baseUrl },
1347
+ body: JSON.stringify(request)
1348
+ });
1349
+ const raw = await res.json();
1350
+ const data = raw && (raw.data ?? (raw.token || raw.user ? { token: raw.token, user: raw.user } : void 0));
1351
+ const normalized = data ? { ...raw, data } : raw;
1352
+ if (normalized.data?.token) {
1353
+ this.token = normalized.data.token;
1354
+ }
1355
+ return normalized;
1356
+ },
1357
+ /**
1358
+ * Initiate OAuth sign-in via a social or OIDC provider.
1359
+ *
1360
+ * - Social providers (Google, GitHub, etc.): calls POST /sign-in/social with `{ provider }`.
1361
+ * - OIDC/enterprise providers: calls POST /sign-in/oauth2 with `{ providerId }`.
1362
+ *
1363
+ * After the provider callback better-auth sets the session cookie and redirects to `callbackURL`.
1364
+ */
1365
+ signInWithProvider: async (provider, opts) => {
1366
+ if (typeof window === "undefined") {
1367
+ throw new Error("signInWithProvider requires a browser environment");
1368
+ }
1369
+ const route = this.getRoute("auth");
1370
+ const callbackURL = opts?.callbackURL ?? window.location.origin + "/login";
1371
+ const isOidc = opts?.type === "oidc";
1372
+ const endpoint = isOidc ? "/sign-in/oauth2" : "/sign-in/social";
1373
+ const body = isOidc ? { providerId: provider, callbackURL } : { provider, callbackURL };
1374
+ if (opts?.errorCallbackURL) body.errorCallbackURL = opts.errorCallbackURL;
1375
+ const res = await this.fetch(`${this.baseUrl}${route}${endpoint}`, {
1376
+ method: "POST",
1377
+ body: JSON.stringify(body)
1378
+ });
1379
+ const data = await res.json();
1380
+ const redirectUrl = data?.url ?? data?.data?.url;
1381
+ if (redirectUrl) {
1382
+ window.location.assign(redirectUrl);
1383
+ } else {
1384
+ throw new Error(`signInWithProvider: no redirect URL returned for provider "${provider}"`);
1385
+ }
1386
+ },
1387
+ /**
1388
+ * Refresh an authentication token
1389
+ * Note: better-auth handles token refresh automatically via /get-session
1390
+ * @param _refreshToken - Not used (better-auth handles refresh automatically)
1391
+ */
1392
+ refreshToken: async (_refreshToken) => {
1393
+ const route = this.getRoute("auth");
1394
+ const res = await this.fetch(`${this.baseUrl}${route}/get-session`, {
1395
+ method: "GET"
1396
+ });
677
1397
  const data = await res.json();
678
1398
  if (data.data?.token) {
679
1399
  this.token = data.data.token;
@@ -681,54 +1401,262 @@ var ObjectStackClient = class {
681
1401
  return data;
682
1402
  },
683
1403
  /**
684
- * Logout current user
685
- * Uses better-auth endpoint: POST /sign-out
1404
+ * Probe the framework-only `/auth/bootstrap-status` endpoint to determine
1405
+ * whether the very first owner has been provisioned. The Account portal's
1406
+ * `/setup` route uses this to decide whether to render the bootstrap form
1407
+ * or bounce the user straight to `/login`.
1408
+ */
1409
+ bootstrapStatus: async () => {
1410
+ const route = this.getRoute("auth");
1411
+ const res = await this.fetch(`${this.baseUrl}${route}/bootstrap-status`);
1412
+ const data = await res.json();
1413
+ const payload = data?.data ?? data;
1414
+ return { hasOwner: !!payload?.hasOwner };
1415
+ },
1416
+ /**
1417
+ * Update the current user's profile.
1418
+ *
1419
+ * better-auth: POST /update-user — accepts `{ name?, image?, ... }`
1420
+ * (any custom user fields configured on the server). Returns the
1421
+ * updated user.
1422
+ */
1423
+ updateUser: async (data) => {
1424
+ const route = this.getRoute("auth");
1425
+ const res = await this.fetch(`${this.baseUrl}${route}/update-user`, {
1426
+ method: "POST",
1427
+ body: JSON.stringify(data)
1428
+ });
1429
+ return res.json();
1430
+ },
1431
+ /**
1432
+ * Change the current user's password (email/password accounts only).
1433
+ *
1434
+ * better-auth: POST /change-password.
1435
+ * Set `revokeOtherSessions: true` to invalidate every other session
1436
+ * after the change.
1437
+ */
1438
+ changePassword: async (req) => {
1439
+ const route = this.getRoute("auth");
1440
+ const res = await this.fetch(`${this.baseUrl}${route}/change-password`, {
1441
+ method: "POST",
1442
+ body: JSON.stringify(req)
1443
+ });
1444
+ return res.json();
1445
+ },
1446
+ /**
1447
+ * Begin a change-email flow. better-auth sends a verification mail to
1448
+ * the new address; the change only takes effect after the user clicks
1449
+ * the link.
1450
+ *
1451
+ * better-auth: POST /change-email — `{ newEmail, callbackURL? }`.
1452
+ */
1453
+ changeEmail: async (req) => {
1454
+ const route = this.getRoute("auth");
1455
+ const res = await this.fetch(`${this.baseUrl}${route}/change-email`, {
1456
+ method: "POST",
1457
+ body: JSON.stringify(req)
1458
+ });
1459
+ return res.json();
1460
+ },
1461
+ /**
1462
+ * Re-send the email-verification link to the current user (or any
1463
+ * address when called as an admin). better-auth: POST /send-verification-email.
686
1464
  */
687
- logout: async () => {
1465
+ sendVerificationEmail: async (req) => {
688
1466
  const route = this.getRoute("auth");
689
- await this.fetch(`${this.baseUrl}${route}/sign-out`, { method: "POST" });
690
- this.token = void 0;
1467
+ const res = await this.fetch(`${this.baseUrl}${route}/send-verification-email`, {
1468
+ method: "POST",
1469
+ body: JSON.stringify(req)
1470
+ });
1471
+ return res.json();
691
1472
  },
692
1473
  /**
693
- * Get current user session
694
- * Uses better-auth endpoint: GET /get-session
1474
+ * Verify an email-verification token (the link target).
1475
+ *
1476
+ * better-auth: GET /verify-email?token=…&callbackURL=…
695
1477
  */
696
- me: async () => {
1478
+ verifyEmail: async (params) => {
697
1479
  const route = this.getRoute("auth");
698
- const res = await this.fetch(`${this.baseUrl}${route}/get-session`);
1480
+ const url = new URL(`${this.baseUrl}${route}/verify-email`);
1481
+ url.searchParams.set("token", params.token);
1482
+ if (params.callbackURL) url.searchParams.set("callbackURL", params.callbackURL);
1483
+ const res = await this.fetch(url.toString());
699
1484
  return res.json();
700
1485
  },
701
1486
  /**
702
- * Register a new user account
703
- * Uses better-auth endpoint: POST /sign-up/email
1487
+ * Permanently delete the current user. better-auth supports two flows:
1488
+ *
1489
+ * 1. With a fresh-session password challenge: POST `{ password }`.
1490
+ * 2. With an emailed deletion-confirmation token: POST `{ token }`,
1491
+ * typically following an out-of-band confirmation step.
1492
+ *
1493
+ * Server policy decides which is required; pass whichever you have.
704
1494
  */
705
- register: async (request) => {
1495
+ deleteUser: async (req) => {
706
1496
  const route = this.getRoute("auth");
707
- const res = await this.fetch(`${this.baseUrl}${route}/sign-up/email`, {
1497
+ const res = await this.fetch(`${this.baseUrl}${route}/delete-user`, {
708
1498
  method: "POST",
709
- body: JSON.stringify(request)
1499
+ body: JSON.stringify(req)
710
1500
  });
711
- const data = await res.json();
712
- if (data.data?.token) {
713
- this.token = data.data.token;
1501
+ this.token = void 0;
1502
+ return res.json();
1503
+ },
1504
+ /**
1505
+ * Active-session management. Wraps better-auth's session endpoints so
1506
+ * the Account portal's `/account/sessions` page can list every device
1507
+ * the user is signed in from and revoke them individually or in bulk.
1508
+ */
1509
+ sessions: {
1510
+ /** better-auth: GET /list-sessions — returns the current user's sessions. */
1511
+ list: async () => {
1512
+ const route = this.getRoute("auth");
1513
+ const res = await this.fetch(`${this.baseUrl}${route}/list-sessions`);
1514
+ const data = await res.json();
1515
+ const sessions = Array.isArray(data) ? data : data?.data ?? data?.sessions ?? [];
1516
+ return { sessions };
1517
+ },
1518
+ /** better-auth: POST /revoke-session — revoke a single session by token. */
1519
+ revoke: async (token) => {
1520
+ const route = this.getRoute("auth");
1521
+ const res = await this.fetch(`${this.baseUrl}${route}/revoke-session`, {
1522
+ method: "POST",
1523
+ body: JSON.stringify({ token })
1524
+ });
1525
+ return res.json();
1526
+ },
1527
+ /** better-auth: POST /revoke-other-sessions — keep current, kill the rest. */
1528
+ revokeOthers: async () => {
1529
+ const route = this.getRoute("auth");
1530
+ const res = await this.fetch(`${this.baseUrl}${route}/revoke-other-sessions`, {
1531
+ method: "POST",
1532
+ body: "{}"
1533
+ });
1534
+ return res.json();
1535
+ },
1536
+ /** better-auth: POST /revoke-sessions — kill every session for this user. */
1537
+ revokeAll: async () => {
1538
+ const route = this.getRoute("auth");
1539
+ const res = await this.fetch(`${this.baseUrl}${route}/revoke-sessions`, {
1540
+ method: "POST",
1541
+ body: "{}"
1542
+ });
1543
+ this.token = void 0;
1544
+ return res.json();
714
1545
  }
715
- return data;
716
1546
  },
717
1547
  /**
718
- * Refresh an authentication token
719
- * Note: better-auth handles token refresh automatically via /get-session
720
- * @param _refreshToken - Not used (better-auth handles refresh automatically)
1548
+ * Two-factor authentication (TOTP + backup codes). Requires the
1549
+ * `twoFactor` plugin to be enabled on the server (see
1550
+ * `plugin-auth` config). Endpoints live under `/two-factor/*`.
721
1551
  */
722
- refreshToken: async (_refreshToken) => {
723
- const route = this.getRoute("auth");
724
- const res = await this.fetch(`${this.baseUrl}${route}/get-session`, {
725
- method: "GET"
726
- });
727
- const data = await res.json();
728
- if (data.data?.token) {
729
- this.token = data.data.token;
1552
+ twoFactor: {
1553
+ /**
1554
+ * Start enrolment. Server returns a TOTP URI (`otpauth://...`) which
1555
+ * the UI renders as a QR code; the user then calls `verifyTotp` to
1556
+ * confirm and finish enabling.
1557
+ */
1558
+ enable: async (req) => {
1559
+ const route = this.getRoute("auth");
1560
+ const res = await this.fetch(`${this.baseUrl}${route}/two-factor/enable`, {
1561
+ method: "POST",
1562
+ body: JSON.stringify(req)
1563
+ });
1564
+ const data = await res.json();
1565
+ return data?.data ?? data;
1566
+ },
1567
+ /**
1568
+ * Confirm a TOTP code — used to finalise enrolment after `enable()`
1569
+ * or to step up an existing 2FA-enabled session. `trustDevice` (when
1570
+ * supported by the server config) suppresses the 2FA challenge on
1571
+ * this browser for the configured trust period.
1572
+ */
1573
+ verifyTotp: async (req) => {
1574
+ const route = this.getRoute("auth");
1575
+ const res = await this.fetch(`${this.baseUrl}${route}/two-factor/verify-totp`, {
1576
+ method: "POST",
1577
+ body: JSON.stringify(req)
1578
+ });
1579
+ return res.json();
1580
+ },
1581
+ /** Disable 2FA for the current user. Requires the password again. */
1582
+ disable: async (req) => {
1583
+ const route = this.getRoute("auth");
1584
+ const res = await this.fetch(`${this.baseUrl}${route}/two-factor/disable`, {
1585
+ method: "POST",
1586
+ body: JSON.stringify(req)
1587
+ });
1588
+ return res.json();
1589
+ },
1590
+ /**
1591
+ * Issue a fresh set of backup codes (invalidating any previous set).
1592
+ * Display them once — the server only stores hashes.
1593
+ */
1594
+ generateBackupCodes: async (req) => {
1595
+ const route = this.getRoute("auth");
1596
+ const res = await this.fetch(`${this.baseUrl}${route}/two-factor/generate-backup-codes`, {
1597
+ method: "POST",
1598
+ body: JSON.stringify(req)
1599
+ });
1600
+ const data = await res.json();
1601
+ return data?.data ?? data;
1602
+ },
1603
+ /**
1604
+ * Verify a 2FA backup code in lieu of a TOTP. Useful as a recovery
1605
+ * affordance when the user has lost their authenticator app.
1606
+ */
1607
+ verifyBackupCode: async (req) => {
1608
+ const route = this.getRoute("auth");
1609
+ const res = await this.fetch(`${this.baseUrl}${route}/two-factor/verify-backup-code`, {
1610
+ method: "POST",
1611
+ body: JSON.stringify(req)
1612
+ });
1613
+ return res.json();
1614
+ }
1615
+ },
1616
+ /**
1617
+ * Linked credentials — i.e. the rows in better-auth's `account` table
1618
+ * (one per provider × user). Lets the user see and unlink their social
1619
+ * / OIDC connections from the Account portal.
1620
+ */
1621
+ accounts: {
1622
+ /** better-auth: GET /list-accounts */
1623
+ list: async () => {
1624
+ const route = this.getRoute("auth");
1625
+ const res = await this.fetch(`${this.baseUrl}${route}/list-accounts`);
1626
+ const data = await res.json();
1627
+ const accounts = Array.isArray(data) ? data : data?.data ?? data?.accounts ?? [];
1628
+ return { accounts };
1629
+ },
1630
+ /**
1631
+ * Unlink a provider connection.
1632
+ * better-auth: POST /unlink-account — `{ providerId, accountId? }`.
1633
+ * `accountId` is required when the user has more than one account
1634
+ * for the same provider.
1635
+ */
1636
+ unlink: async (req) => {
1637
+ const route = this.getRoute("auth");
1638
+ const res = await this.fetch(`${this.baseUrl}${route}/unlink-account`, {
1639
+ method: "POST",
1640
+ body: JSON.stringify(req)
1641
+ });
1642
+ return res.json();
1643
+ },
1644
+ /**
1645
+ * Link an additional social provider to the current user.
1646
+ * better-auth: POST /link-social — `{ provider, callbackURL }`. The
1647
+ * server returns a redirect URL; the caller should `window.location`
1648
+ * to it (mirroring `signInWithProvider`).
1649
+ */
1650
+ linkSocial: async (req) => {
1651
+ const route = this.getRoute("auth");
1652
+ const callbackURL = req.callbackURL ?? (typeof window !== "undefined" ? window.location.href : void 0);
1653
+ const res = await this.fetch(`${this.baseUrl}${route}/link-social`, {
1654
+ method: "POST",
1655
+ body: JSON.stringify({ provider: req.provider, callbackURL })
1656
+ });
1657
+ const data = await res.json();
1658
+ return data?.data ?? data;
730
1659
  }
731
- return data;
732
1660
  }
733
1661
  };
734
1662
  /**
@@ -935,6 +1863,46 @@ var ObjectStackClient = class {
935
1863
  const res = await this.fetch(`${this.baseUrl}${route}/${flowName}/runs/${runId}`);
936
1864
  return this.unwrapResponse(res);
937
1865
  }
1866
+ },
1867
+ /**
1868
+ * Flat aliases mirroring the ScopedProjectClient.automation surface so
1869
+ * Studio (and other consumers) can use the same call shape regardless of
1870
+ * whether they hold a scoped or unscoped client.
1871
+ */
1872
+ /** Alias for `automation.get` — fetch a flow definition by name. */
1873
+ getFlow: async (name) => {
1874
+ const route = this.getRoute("automation");
1875
+ const res = await this.fetch(`${this.baseUrl}${route}/${encodeURIComponent(name)}`);
1876
+ return this.unwrapResponse(res);
1877
+ },
1878
+ /** Execute (trigger) a flow with an execution context. */
1879
+ execute: async (name, ctx) => {
1880
+ const route = this.getRoute("automation");
1881
+ const res = await this.fetch(`${this.baseUrl}${route}/${encodeURIComponent(name)}/trigger`, {
1882
+ method: "POST",
1883
+ body: JSON.stringify(ctx ?? {})
1884
+ });
1885
+ return this.unwrapResponse(res);
1886
+ },
1887
+ /** Alias for `automation.runs.list`. */
1888
+ listRuns: async (flowName, opts) => {
1889
+ const route = this.getRoute("automation");
1890
+ const params = new URLSearchParams();
1891
+ if (opts?.limit != null) params.set("limit", String(opts.limit));
1892
+ if (opts?.cursor) params.set("cursor", opts.cursor);
1893
+ const qs = params.toString();
1894
+ const res = await this.fetch(
1895
+ `${this.baseUrl}${route}/${encodeURIComponent(flowName)}/runs${qs ? `?${qs}` : ""}`
1896
+ );
1897
+ return this.unwrapResponse(res);
1898
+ },
1899
+ /** Alias for `automation.runs.get`. */
1900
+ getRun: async (flowName, runId) => {
1901
+ const route = this.getRoute("automation");
1902
+ const res = await this.fetch(
1903
+ `${this.baseUrl}${route}/${encodeURIComponent(flowName)}/runs/${encodeURIComponent(runId)}`
1904
+ );
1905
+ return this.unwrapResponse(res);
938
1906
  }
939
1907
  };
940
1908
  /**
@@ -1625,8 +2593,9 @@ var ObjectStackClient = class {
1625
2593
  };
1626
2594
  this.baseUrl = config.baseUrl.replace(/\/$/, "");
1627
2595
  this.token = config.token;
2596
+ this.projectId = config.projectId;
1628
2597
  this.fetchImpl = config.fetch || globalThis.fetch.bind(globalThis);
1629
- this.logger = config.logger || (0, import_core.createLogger)({
2598
+ this.logger = config.logger || (0, import_logger.createLogger)({
1630
2599
  level: config.debug ? "debug" : "info",
1631
2600
  format: "pretty"
1632
2601
  });
@@ -1641,6 +2610,18 @@ var ObjectStackClient = class {
1641
2610
  try {
1642
2611
  let data;
1643
2612
  try {
2613
+ const discoveryUrl = `${this.baseUrl}/api/v1/discovery`;
2614
+ this.logger.debug("Probing protocol-standard discovery endpoint", { url: discoveryUrl });
2615
+ const res = await this.fetchImpl(discoveryUrl);
2616
+ if (res.ok) {
2617
+ const body = await res.json();
2618
+ data = body.data || body;
2619
+ this.logger.debug("Discovered via /api/v1/discovery");
2620
+ }
2621
+ } catch (e) {
2622
+ this.logger.debug("Protocol-standard discovery probe failed", { error: e.message });
2623
+ }
2624
+ if (!data) {
1644
2625
  let wellKnownUrl;
1645
2626
  try {
1646
2627
  const url = new URL(this.baseUrl);
@@ -1648,22 +2629,10 @@ var ObjectStackClient = class {
1648
2629
  } catch {
1649
2630
  wellKnownUrl = "/.well-known/objectstack";
1650
2631
  }
1651
- this.logger.debug("Probing .well-known discovery", { url: wellKnownUrl });
2632
+ this.logger.debug("Falling back to .well-known discovery", { url: wellKnownUrl });
1652
2633
  const res = await this.fetchImpl(wellKnownUrl);
1653
- if (res.ok) {
1654
- const body = await res.json();
1655
- data = body.data || body;
1656
- this.logger.debug("Discovered via .well-known");
1657
- }
1658
- } catch (e) {
1659
- this.logger.debug("Standard discovery probe failed", { error: e.message });
1660
- }
1661
- if (!data) {
1662
- const fallbackUrl = `${this.baseUrl}/api/v1/discovery`;
1663
- this.logger.debug("Falling back to standard discovery endpoint", { url: fallbackUrl });
1664
- const res = await this.fetchImpl(fallbackUrl);
1665
2634
  if (!res.ok) {
1666
- throw new Error(`Failed to connect to ${fallbackUrl}: ${res.statusText}`);
2635
+ throw new Error(`Failed to connect to ${wellKnownUrl}: ${res.statusText}`);
1667
2636
  }
1668
2637
  const body = await res.json();
1669
2638
  data = body.data || body;
@@ -1701,6 +2670,64 @@ var ObjectStackClient = class {
1701
2670
  }
1702
2671
  return result;
1703
2672
  }
2673
+ /**
2674
+ * Project-scoped client factory.
2675
+ *
2676
+ * Returns a thin wrapper around the data / meta / packages namespaces that
2677
+ * prefixes every request with `/api/v1/projects/:projectId/...`. Use this
2678
+ * when the server has `enableProjectScoping: true` in its REST API config.
2679
+ *
2680
+ * Backward compatibility: `client.data.*`, `client.meta.*`, and
2681
+ * `client.packages.*` continue to work unchanged; they hit unscoped routes
2682
+ * and rely on hostname / `X-Project-Id` header / session resolution.
2683
+ *
2684
+ * @example
2685
+ * ```ts
2686
+ * const scoped = client.project('00000000-0000-0000-0000-000000000001');
2687
+ * const tasks = await scoped.data.find('task', { top: 10 });
2688
+ * const objects = await scoped.meta.getItems('object');
2689
+ * ```
2690
+ */
2691
+ project(projectId) {
2692
+ if (!projectId) {
2693
+ throw new Error("[ObjectStack] project(id): projectId is required");
2694
+ }
2695
+ return new ScopedProjectClient(this, projectId);
2696
+ }
2697
+ // ── Internal accessors exposed to ScopedProjectClient ────────────────
2698
+ // The scoped client lives in the same module so using module-level access
2699
+ // works; TypeScript requires these to be accessible, so we expose them via
2700
+ // small protected getters that keep the public surface unchanged.
2701
+ /** @internal */
2702
+ _baseUrl() {
2703
+ return this.baseUrl;
2704
+ }
2705
+ /** @internal */
2706
+ _fetch(url, init) {
2707
+ return this.fetch(url, init);
2708
+ }
2709
+ /** @internal */
2710
+ _unwrap(res) {
2711
+ return this.unwrapResponse(res);
2712
+ }
2713
+ /** @internal */
2714
+ _isFilterAST(v) {
2715
+ return this.isFilterAST(v);
2716
+ }
2717
+ /**
2718
+ * Update the active project id used for subsequent requests.
2719
+ * Pass `undefined` to clear (falls back to the session default).
2720
+ */
2721
+ setProjectId(projectId) {
2722
+ this.projectId = projectId;
2723
+ this.logger.debug("Active project changed", { projectId });
2724
+ }
2725
+ /**
2726
+ * Current active project id (if set).
2727
+ */
2728
+ getProjectId() {
2729
+ return this.projectId;
2730
+ }
1704
2731
  /**
1705
2732
  * Event Subscription API
1706
2733
  * Provides real-time event subscriptions for metadata and data changes
@@ -1741,6 +2768,9 @@ var ObjectStackClient = class {
1741
2768
  if (this.token) {
1742
2769
  headers["Authorization"] = `Bearer ${this.token}`;
1743
2770
  }
2771
+ if (this.projectId) {
2772
+ headers["X-Project-Id"] = this.projectId;
2773
+ }
1744
2774
  const res = await this.fetchImpl(url, { ...options, headers });
1745
2775
  this.logger.debug("HTTP response", {
1746
2776
  method: options.method || "GET",
@@ -1807,12 +2837,247 @@ var ObjectStackClient = class {
1807
2837
  return routeMap[type] || `/api/v1/${type}`;
1808
2838
  }
1809
2839
  };
2840
+ var ScopedProjectClient = class {
2841
+ constructor(parent, projectId) {
2842
+ /**
2843
+ * Metadata operations scoped to this project.
2844
+ */
2845
+ this.meta = {
2846
+ getTypes: async () => {
2847
+ const res = await this.parent._fetch(this.url("/meta"));
2848
+ return this.parent._unwrap(res);
2849
+ },
2850
+ getItems: async (type, options) => {
2851
+ const params = new URLSearchParams();
2852
+ if (options?.packageId) params.set("package", options.packageId);
2853
+ const qs = params.toString();
2854
+ const res = await this.parent._fetch(this.url(`/meta/${type}${qs ? `?${qs}` : ""}`));
2855
+ return this.parent._unwrap(res);
2856
+ },
2857
+ getItem: async (type, name, options) => {
2858
+ const params = new URLSearchParams();
2859
+ if (options?.packageId) params.set("package", options.packageId);
2860
+ const qs = params.toString();
2861
+ const res = await this.parent._fetch(this.url(`/meta/${type}/${name}${qs ? `?${qs}` : ""}`));
2862
+ return this.parent._unwrap(res);
2863
+ },
2864
+ saveItem: async (type, name, item) => {
2865
+ const res = await this.parent._fetch(this.url(`/meta/${type}/${name}`), {
2866
+ method: "PUT",
2867
+ body: JSON.stringify(item)
2868
+ });
2869
+ return this.parent._unwrap(res);
2870
+ },
2871
+ deleteItem: async (type, name) => {
2872
+ const res = await this.parent._fetch(this.url(`/meta/${encodeURIComponent(type)}/${encodeURIComponent(name)}`), {
2873
+ method: "DELETE"
2874
+ });
2875
+ return this.parent._unwrap(res);
2876
+ }
2877
+ };
2878
+ /**
2879
+ * Data operations scoped to this project.
2880
+ *
2881
+ * Mirrors the query / find / get / create / update / delete / batch
2882
+ * surface on {@link ObjectStackClient}. URL construction differs only
2883
+ * in the prefix — query parameter serialization is identical.
2884
+ */
2885
+ this.data = {
2886
+ query: async (object, query) => {
2887
+ const res = await this.parent._fetch(this.url(`/data/${object}/query`), {
2888
+ method: "POST",
2889
+ body: JSON.stringify(query)
2890
+ });
2891
+ return this.parent._unwrap(res);
2892
+ },
2893
+ find: async (object, options = {}) => {
2894
+ const queryParams = new URLSearchParams();
2895
+ const v2 = options;
2896
+ const normalizedOptions = {};
2897
+ if ("where" in options || "fields" in options || "orderBy" in options || "offset" in options) {
2898
+ if (v2.where) normalizedOptions.filter = v2.where;
2899
+ if (v2.fields) normalizedOptions.select = v2.fields;
2900
+ if (v2.orderBy) normalizedOptions.sort = v2.orderBy;
2901
+ if (v2.limit != null) normalizedOptions.top = v2.limit;
2902
+ if (v2.offset != null) normalizedOptions.skip = v2.offset;
2903
+ if (v2.aggregations) normalizedOptions.aggregations = v2.aggregations;
2904
+ if (v2.groupBy) normalizedOptions.groupBy = v2.groupBy;
2905
+ } else {
2906
+ Object.assign(normalizedOptions, options);
2907
+ }
2908
+ if (normalizedOptions.top) queryParams.set("top", normalizedOptions.top.toString());
2909
+ if (normalizedOptions.skip) queryParams.set("skip", normalizedOptions.skip.toString());
2910
+ if (normalizedOptions.sort) {
2911
+ if (Array.isArray(normalizedOptions.sort) && typeof normalizedOptions.sort[0] === "object") {
2912
+ queryParams.set("sort", JSON.stringify(normalizedOptions.sort));
2913
+ } else {
2914
+ const sortVal = Array.isArray(normalizedOptions.sort) ? normalizedOptions.sort.join(",") : normalizedOptions.sort;
2915
+ queryParams.set("sort", sortVal);
2916
+ }
2917
+ }
2918
+ if (normalizedOptions.select) {
2919
+ queryParams.set("select", normalizedOptions.select.join(","));
2920
+ }
2921
+ const filterValue = normalizedOptions.filter ?? normalizedOptions.filters;
2922
+ if (filterValue) {
2923
+ if (this.parent._isFilterAST(filterValue) || Array.isArray(filterValue)) {
2924
+ queryParams.set("filter", JSON.stringify(filterValue));
2925
+ } else if (typeof filterValue === "object" && filterValue !== null) {
2926
+ Object.entries(filterValue).forEach(([k, v]) => {
2927
+ if (v !== void 0 && v !== null) {
2928
+ queryParams.append(k, String(v));
2929
+ }
2930
+ });
2931
+ }
2932
+ }
2933
+ if (normalizedOptions.aggregations) {
2934
+ queryParams.set("aggregations", JSON.stringify(normalizedOptions.aggregations));
2935
+ }
2936
+ if (normalizedOptions.groupBy) {
2937
+ queryParams.set("groupBy", normalizedOptions.groupBy.join(","));
2938
+ }
2939
+ const qs = queryParams.toString();
2940
+ const res = await this.parent._fetch(this.url(`/data/${object}${qs ? `?${qs}` : ""}`));
2941
+ return this.parent._unwrap(res);
2942
+ },
2943
+ get: async (object, id) => {
2944
+ const res = await this.parent._fetch(this.url(`/data/${object}/${id}`));
2945
+ return this.parent._unwrap(res);
2946
+ },
2947
+ create: async (object, data) => {
2948
+ const res = await this.parent._fetch(this.url(`/data/${object}`), {
2949
+ method: "POST",
2950
+ body: JSON.stringify(data)
2951
+ });
2952
+ return this.parent._unwrap(res);
2953
+ },
2954
+ createMany: async (object, data) => {
2955
+ const res = await this.parent._fetch(this.url(`/data/${object}/createMany`), {
2956
+ method: "POST",
2957
+ body: JSON.stringify(data)
2958
+ });
2959
+ return this.parent._unwrap(res);
2960
+ },
2961
+ update: async (object, id, data) => {
2962
+ const res = await this.parent._fetch(this.url(`/data/${object}/${id}`), {
2963
+ method: "PATCH",
2964
+ body: JSON.stringify(data)
2965
+ });
2966
+ return this.parent._unwrap(res);
2967
+ },
2968
+ batch: async (object, request) => {
2969
+ const res = await this.parent._fetch(this.url(`/data/${object}/batch`), {
2970
+ method: "POST",
2971
+ body: JSON.stringify(request)
2972
+ });
2973
+ return this.parent._unwrap(res);
2974
+ },
2975
+ updateMany: async (object, records, options) => {
2976
+ const request = { records, options };
2977
+ const res = await this.parent._fetch(this.url(`/data/${object}/updateMany`), {
2978
+ method: "POST",
2979
+ body: JSON.stringify(request)
2980
+ });
2981
+ return this.parent._unwrap(res);
2982
+ },
2983
+ delete: async (object, id) => {
2984
+ const res = await this.parent._fetch(this.url(`/data/${object}/${id}`), {
2985
+ method: "DELETE"
2986
+ });
2987
+ return this.parent._unwrap(res);
2988
+ },
2989
+ deleteMany: async (object, ids, options) => {
2990
+ const request = { ids, options };
2991
+ const res = await this.parent._fetch(this.url(`/data/${object}/deleteMany`), {
2992
+ method: "POST",
2993
+ body: JSON.stringify(request)
2994
+ });
2995
+ return this.parent._unwrap(res);
2996
+ }
2997
+ };
2998
+ /**
2999
+ * Package management scoped to this project.
3000
+ * Only the read-path is exposed here — publish / delete remain on the
3001
+ * global `client.packages` namespace for now, pending dedicated per-project
3002
+ * package tests.
3003
+ */
3004
+ this.packages = {
3005
+ list: async () => {
3006
+ const res = await this.parent._fetch(this.url("/packages"));
3007
+ return this.parent._unwrap(res);
3008
+ },
3009
+ get: async (id, version) => {
3010
+ const qs = version ? `?version=${encodeURIComponent(version)}` : "";
3011
+ const res = await this.parent._fetch(this.url(`/packages/${encodeURIComponent(id)}${qs}`));
3012
+ return this.parent._unwrap(res);
3013
+ }
3014
+ };
3015
+ /**
3016
+ * Automation (Flow) operations scoped to this project.
3017
+ *
3018
+ * Thin wrapper around the dispatcher's automation routes, mounted under
3019
+ * `/api/v1/projects/:projectId/automation/...`. Surface mirrors the methods
3020
+ * needed by Studio's Flow viewer: read flow definition, execute (trigger),
3021
+ * list runs, fetch a single run.
3022
+ */
3023
+ this.automation = {
3024
+ /** Fetch a flow definition by name. */
3025
+ getFlow: async (name) => {
3026
+ const res = await this.parent._fetch(this.url(`/automation/${encodeURIComponent(name)}`));
3027
+ return this.parent._unwrap(res);
3028
+ },
3029
+ /**
3030
+ * Execute (trigger) a flow by name. The request body is forwarded as the
3031
+ * automation execution context (e.g. `{ params, trigger }`).
3032
+ */
3033
+ execute: async (name, ctx) => {
3034
+ const res = await this.parent._fetch(this.url(`/automation/${encodeURIComponent(name)}/trigger`), {
3035
+ method: "POST",
3036
+ body: JSON.stringify(ctx ?? {})
3037
+ });
3038
+ return this.parent._unwrap(res);
3039
+ },
3040
+ /** List recent runs for a flow. */
3041
+ listRuns: async (flowName, opts) => {
3042
+ const params = new URLSearchParams();
3043
+ if (opts?.limit != null) params.set("limit", String(opts.limit));
3044
+ if (opts?.cursor) params.set("cursor", opts.cursor);
3045
+ const qs = params.toString();
3046
+ const res = await this.parent._fetch(
3047
+ this.url(`/automation/${encodeURIComponent(flowName)}/runs${qs ? `?${qs}` : ""}`)
3048
+ );
3049
+ return this.parent._unwrap(res);
3050
+ },
3051
+ /** Fetch a single run (with step log) for a flow. */
3052
+ getRun: async (flowName, runId) => {
3053
+ const res = await this.parent._fetch(
3054
+ this.url(`/automation/${encodeURIComponent(flowName)}/runs/${encodeURIComponent(runId)}`)
3055
+ );
3056
+ return this.parent._unwrap(res);
3057
+ }
3058
+ };
3059
+ this.parent = parent;
3060
+ this.projectId = projectId;
3061
+ }
3062
+ /** The projectId this client is scoped to. */
3063
+ getProjectId() {
3064
+ return this.projectId;
3065
+ }
3066
+ /** Prefix segment inserted between the baseUrl and the resource path. */
3067
+ scope() {
3068
+ return `/api/v1/projects/${encodeURIComponent(this.projectId)}`;
3069
+ }
3070
+ url(suffix) {
3071
+ return `${this.parent._baseUrl()}${this.scope()}${suffix}`;
3072
+ }
3073
+ };
1810
3074
  // Annotate the CommonJS export names for ESM import in node:
1811
3075
  0 && (module.exports = {
1812
3076
  FilterBuilder,
1813
3077
  ObjectStackClient,
1814
3078
  QueryBuilder,
1815
3079
  RealtimeAPI,
3080
+ ScopedProjectClient,
1816
3081
  createFilter,
1817
3082
  createQuery
1818
3083
  });