@ragable/sdk 0.6.20 → 0.6.22

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
@@ -56,7 +56,10 @@ __export(index_exports, {
56
56
  ShiftClient: () => ShiftClient,
57
57
  Transport: () => Transport,
58
58
  asPostgrestResponse: () => asPostgrestResponse,
59
+ assertPostgrestSuccess: () => assertPostgrestSuccess,
59
60
  bindFetch: () => bindFetch,
61
+ collectionRecordToRowWithMeta: () => collectionRecordToRowWithMeta,
62
+ collectionRecordsToRowWithMeta: () => collectionRecordsToRowWithMeta,
60
63
  createBrowserClient: () => createBrowserClient,
61
64
  createClient: () => createClient,
62
65
  createRagPipeline: () => createRagPipeline,
@@ -72,7 +75,9 @@ __export(index_exports, {
72
75
  normalizeBrowserApiBase: () => normalizeBrowserApiBase,
73
76
  parseSseDataLine: () => parseSseDataLine,
74
77
  parseTransportResponse: () => parseTransportResponse,
75
- readSseStream: () => readSseStream
78
+ readSseStream: () => readSseStream,
79
+ toRagableResult: () => toRagableResult,
80
+ unwrapPostgrest: () => unwrapPostgrest
76
81
  });
77
82
  module.exports = __toCommonJS(index_exports);
78
83
 
@@ -701,6 +706,17 @@ async function parseTransportResponse(response) {
701
706
  }
702
707
 
703
708
  // src/browser-postgrest.ts
709
+ function toRagableResult(r) {
710
+ if (r.error) return { ok: false, error: r.error };
711
+ return { ok: true, value: r.data };
712
+ }
713
+ function assertPostgrestSuccess(r) {
714
+ if (r.error) throw r.error;
715
+ }
716
+ function unwrapPostgrest(r) {
717
+ if (r.error) throw r.error;
718
+ return r.data;
719
+ }
704
720
  async function asPostgrestResponse(fn) {
705
721
  try {
706
722
  const data = await fn();
@@ -2286,24 +2302,71 @@ var RagableBrowserAuthClient = class {
2286
2302
  return this.auth.getSession();
2287
2303
  }
2288
2304
  };
2305
+ function collectionRecordToRowWithMeta(record) {
2306
+ const { data, id, createdAt, updatedAt } = record;
2307
+ return { ...data, meta: { id, createdAt, updatedAt } };
2308
+ }
2309
+ function collectionRecordsToRowWithMeta(records) {
2310
+ return records.map(collectionRecordToRowWithMeta);
2311
+ }
2312
+ var FIND_QUERY_KEYS = [
2313
+ "where",
2314
+ "filters",
2315
+ "limit",
2316
+ "offset",
2317
+ "orderBy",
2318
+ "orderDirection",
2319
+ "return"
2320
+ ];
2289
2321
  var BrowserCollectionApi = class {
2290
2322
  constructor(database, name, databaseInstanceId) {
2291
2323
  this.database = database;
2292
2324
  this.name = name;
2293
2325
  this.databaseInstanceId = databaseInstanceId;
2294
- __publicField(this, "find", (whereOrParams = {}) => {
2295
- const hasQueryKeys = ["where", "filters", "limit", "offset", "orderBy", "orderDirection"].some(
2296
- (key) => Object.prototype.hasOwnProperty.call(whereOrParams, key)
2297
- );
2298
- const body = hasQueryKeys ? whereOrParams : { where: whereOrParams };
2299
- return asPostgrestResponse(
2300
- () => this.database._requestCollection(
2301
- "POST",
2302
- `/${encodeURIComponent(this.name)}/find`,
2303
- body,
2304
- this.databaseInstanceId
2305
- )
2306
- );
2326
+ __publicField(this, "requestFind", (body) => asPostgrestResponse(
2327
+ () => this.database._requestCollection(
2328
+ "POST",
2329
+ `/${encodeURIComponent(this.name)}/find`,
2330
+ body,
2331
+ this.databaseInstanceId
2332
+ )
2333
+ ));
2334
+ /**
2335
+ * Query collection rows. Prefer this over the deprecated `find` alias.
2336
+ * Use `return: "flat"` to get {@link CollectionRowWithMeta} without nested `.data`.
2337
+ */
2338
+ __publicField(this, "findMany", async (whereOrParams = {}) => {
2339
+ const { returnMode, body } = this.normalizeFindArgs(whereOrParams);
2340
+ const res = await this.requestFind(body);
2341
+ if (res.error) return res;
2342
+ if (returnMode === "flat") {
2343
+ return {
2344
+ data: collectionRecordsToRowWithMeta(res.data),
2345
+ error: null
2346
+ };
2347
+ }
2348
+ return res;
2349
+ });
2350
+ /**
2351
+ * @deprecated Use {@link BrowserCollectionApi.findMany} — same behavior.
2352
+ */
2353
+ __publicField(this, "find", (whereOrParams = {}) => this.findMany(whereOrParams));
2354
+ /**
2355
+ * At most one row, `data` is the record or `null` if none match (not an error).
2356
+ */
2357
+ __publicField(this, "findFirst", async (whereOrParams = {}) => {
2358
+ const { body } = this.normalizeFindArgs(whereOrParams);
2359
+ const withCap = { ...body, limit: 1, offset: body["offset"] ?? 0 };
2360
+ const res = await this.requestFind(withCap);
2361
+ if (res.error) return res;
2362
+ return { data: res.data[0] ?? null, error: null };
2363
+ });
2364
+ /**
2365
+ * Lookup by primary key `id` (envelope). Equivalent to
2366
+ * `findFirst({ where: { id }, limit: 1 })` with a typed `where.id`.
2367
+ */
2368
+ __publicField(this, "findUnique", async (args) => {
2369
+ return this.findFirst({ where: args.where });
2307
2370
  });
2308
2371
  __publicField(this, "insert", (data) => asPostgrestResponse(
2309
2372
  () => this.database._requestCollection(
@@ -2313,6 +2376,9 @@ var BrowserCollectionApi = class {
2313
2376
  this.databaseInstanceId
2314
2377
  )
2315
2378
  ));
2379
+ /**
2380
+ * Update rows matching `where` (JSON fields, plus envelope `id` / `createdAt` / `updatedAt`).
2381
+ */
2316
2382
  __publicField(this, "update", (where, patch, options) => asPostgrestResponse(
2317
2383
  () => this.database._requestCollection(
2318
2384
  "PATCH",
@@ -2321,6 +2387,15 @@ var BrowserCollectionApi = class {
2321
2387
  this.databaseInstanceId
2322
2388
  )
2323
2389
  ));
2390
+ /**
2391
+ * Like {@link BrowserCollectionApi.update} but the success payload includes
2392
+ * `meta.count` (number of rows returned from the update, bounded by `limit`).
2393
+ */
2394
+ __publicField(this, "updateMany", async (where, patch, options) => {
2395
+ const r = await this.update(where, patch, options);
2396
+ if (r.error) return r;
2397
+ return { data: { records: r.data, meta: { count: r.data.length } }, error: null };
2398
+ });
2324
2399
  __publicField(this, "delete", (where, options) => asPostgrestResponse(
2325
2400
  () => this.database._requestCollection(
2326
2401
  "DELETE",
@@ -2330,6 +2405,15 @@ var BrowserCollectionApi = class {
2330
2405
  )
2331
2406
  ));
2332
2407
  }
2408
+ normalizeFindArgs(whereOrParams) {
2409
+ const hasQueryKeys = typeof whereOrParams === "object" && whereOrParams !== null && FIND_QUERY_KEYS.some(
2410
+ (key) => Object.prototype.hasOwnProperty.call(whereOrParams, key)
2411
+ );
2412
+ const raw = hasQueryKeys ? { ...whereOrParams } : { where: whereOrParams };
2413
+ const returnMode = raw["return"] === "flat" ? "flat" : "envelope";
2414
+ delete raw["return"];
2415
+ return { returnMode, body: raw };
2416
+ }
2333
2417
  };
2334
2418
  var RagableBrowserDatabaseClient = class {
2335
2419
  constructor(options, ragableAuth = null) {
@@ -2724,6 +2808,31 @@ var RagableBrowserAgentsClient = class {
2724
2808
  toUrl(path) {
2725
2809
  return `${normalizeBrowserApiBase()}${path.startsWith("/") ? path : `/${path}`}`;
2726
2810
  }
2811
+ requireWebsiteId() {
2812
+ const websiteId = this.options.websiteId?.trim();
2813
+ if (!websiteId) {
2814
+ throw new RagableError(
2815
+ "websiteId is required for project agent conversation APIs. Use the generated createWebsiteRagableClient() or pass createBrowserClient({ websiteId, ... }).",
2816
+ 400,
2817
+ { code: "SDK_MISSING_WEBSITE_ID" }
2818
+ );
2819
+ }
2820
+ return websiteId;
2821
+ }
2822
+ websiteAgentPath(path) {
2823
+ const websiteId = this.requireWebsiteId();
2824
+ return `/public/organizations/${this.options.organizationId}/websites/${websiteId}${path}`;
2825
+ }
2826
+ async requestJson(path, init = {}) {
2827
+ const response = await this.fetchImpl(this.toUrl(path), init);
2828
+ const payload = await parseMaybeJsonBody(response);
2829
+ if (!response.ok) {
2830
+ const message = extractErrorMessage(payload, response.statusText);
2831
+ throw new RagableError(message, response.status, payload);
2832
+ }
2833
+ return payload;
2834
+ }
2835
+ /** @deprecated Prefer `chatStreamByName(agentName, params)` for project-local `/agents/*.json` agents. */
2727
2836
  async *chatStream(agentId, params) {
2728
2837
  const orgId = this.options.organizationId;
2729
2838
  const body = {
@@ -2753,6 +2862,107 @@ var RagableBrowserAgentsClient = class {
2753
2862
  }
2754
2863
  yield* readSseStream(streamBody);
2755
2864
  }
2865
+ async *chatStreamByName(agentName, params) {
2866
+ const headers = new Headers(this.options.headers);
2867
+ headers.set("Content-Type", "application/json");
2868
+ const response = await this.fetchImpl(
2869
+ this.toUrl(
2870
+ this.websiteAgentPath(
2871
+ `/agents/${encodeURIComponent(agentName)}/chat/stream`
2872
+ )
2873
+ ),
2874
+ {
2875
+ method: "POST",
2876
+ headers,
2877
+ body: JSON.stringify({
2878
+ message: params.message,
2879
+ ...params.history !== void 0 ? { history: params.history } : {}
2880
+ })
2881
+ }
2882
+ );
2883
+ if (!response.ok) {
2884
+ const payload = await parseMaybeJsonBody(response);
2885
+ const message = extractErrorMessage(payload, response.statusText);
2886
+ throw new RagableError(message, response.status, payload);
2887
+ }
2888
+ if (!response.body) return;
2889
+ yield* readSseStream(response.body);
2890
+ }
2891
+ createConversation(params) {
2892
+ const headers = new Headers(this.options.headers);
2893
+ headers.set("Content-Type", "application/json");
2894
+ return this.requestJson(
2895
+ this.websiteAgentPath("/agent-conversations"),
2896
+ {
2897
+ method: "POST",
2898
+ headers,
2899
+ body: JSON.stringify(params)
2900
+ }
2901
+ );
2902
+ }
2903
+ listConversations(params = {}) {
2904
+ const agentName = params.agent_name ?? params.agentName;
2905
+ const qs = agentName ? `?agentName=${encodeURIComponent(agentName)}` : "";
2906
+ return this.requestJson(
2907
+ this.websiteAgentPath(`/agent-conversations${qs}`)
2908
+ );
2909
+ }
2910
+ getConversation(conversationId) {
2911
+ return this.requestJson(
2912
+ this.websiteAgentPath(
2913
+ `/agent-conversations/${encodeURIComponent(conversationId)}`
2914
+ )
2915
+ );
2916
+ }
2917
+ updateConversation(conversationId, data) {
2918
+ const headers = new Headers(this.options.headers);
2919
+ headers.set("Content-Type", "application/json");
2920
+ return this.requestJson(
2921
+ this.websiteAgentPath(
2922
+ `/agent-conversations/${encodeURIComponent(conversationId)}`
2923
+ ),
2924
+ {
2925
+ method: "PATCH",
2926
+ headers,
2927
+ body: JSON.stringify(data)
2928
+ }
2929
+ );
2930
+ }
2931
+ addMessage(conversationOrId, message) {
2932
+ const conversationId = typeof conversationOrId === "string" ? conversationOrId : conversationOrId.id;
2933
+ const headers = new Headers(this.options.headers);
2934
+ headers.set("Content-Type", "application/json");
2935
+ return this.requestJson(
2936
+ this.websiteAgentPath(
2937
+ `/agent-conversations/${encodeURIComponent(conversationId)}/messages`
2938
+ ),
2939
+ {
2940
+ method: "POST",
2941
+ headers,
2942
+ body: JSON.stringify(message)
2943
+ }
2944
+ );
2945
+ }
2946
+ subscribeToConversation(conversationId, callback, options = {}) {
2947
+ let stopped = false;
2948
+ let timer = null;
2949
+ const intervalMs = Math.max(500, options.intervalMs ?? 1500);
2950
+ const tick = async () => {
2951
+ if (stopped) return;
2952
+ try {
2953
+ callback(await this.getConversation(conversationId));
2954
+ } finally {
2955
+ if (!stopped) timer = setTimeout(tick, intervalMs);
2956
+ }
2957
+ };
2958
+ void tick();
2959
+ return {
2960
+ unsubscribe: () => {
2961
+ stopped = true;
2962
+ if (timer) clearTimeout(timer);
2963
+ }
2964
+ };
2965
+ }
2756
2966
  };
2757
2967
  var RagableBrowser = class {
2758
2968
  constructor(options) {
@@ -2923,7 +3133,10 @@ function createRagableServerClient(options) {
2923
3133
  ShiftClient,
2924
3134
  Transport,
2925
3135
  asPostgrestResponse,
3136
+ assertPostgrestSuccess,
2926
3137
  bindFetch,
3138
+ collectionRecordToRowWithMeta,
3139
+ collectionRecordsToRowWithMeta,
2927
3140
  createBrowserClient,
2928
3141
  createClient,
2929
3142
  createRagPipeline,
@@ -2939,6 +3152,8 @@ function createRagableServerClient(options) {
2939
3152
  normalizeBrowserApiBase,
2940
3153
  parseSseDataLine,
2941
3154
  parseTransportResponse,
2942
- readSseStream
3155
+ readSseStream,
3156
+ toRagableResult,
3157
+ unwrapPostgrest
2943
3158
  });
2944
3159
  //# sourceMappingURL=index.js.map