@supacloud/js 0.45.4 → 0.46.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -2309,6 +2309,392 @@ class SupaCloudOAuthServerClient {
2309
2309
  }
2310
2310
  }
2311
2311
 
2312
+ // src/realtime.ts
2313
+ function matchesPostgresFilter(filterStr, record) {
2314
+ if (!filterStr || !filterStr.trim())
2315
+ return true;
2316
+ const eqIdx = filterStr.indexOf("=");
2317
+ if (eqIdx === -1)
2318
+ return true;
2319
+ const col = filterStr.substring(0, eqIdx).trim();
2320
+ const rest = filterStr.substring(eqIdx + 1).trim();
2321
+ const dotIdx = rest.indexOf(".");
2322
+ if (dotIdx === -1)
2323
+ return true;
2324
+ const op = rest.substring(0, dotIdx).trim().toLowerCase();
2325
+ const rawVal = rest.substring(dotIdx + 1).trim();
2326
+ const val = record[col];
2327
+ const strVal = val === null || val === undefined ? "" : String(val);
2328
+ switch (op) {
2329
+ case "eq":
2330
+ return strVal === rawVal;
2331
+ case "neq":
2332
+ return strVal !== rawVal;
2333
+ case "gt": {
2334
+ const nVal = Number(val);
2335
+ const nTarget = Number(rawVal);
2336
+ return !isNaN(nVal) && !isNaN(nTarget) ? nVal > nTarget : strVal > rawVal;
2337
+ }
2338
+ case "gte": {
2339
+ const nVal = Number(val);
2340
+ const nTarget = Number(rawVal);
2341
+ return !isNaN(nVal) && !isNaN(nTarget) ? nVal >= nTarget : strVal >= rawVal;
2342
+ }
2343
+ case "lt": {
2344
+ const nVal = Number(val);
2345
+ const nTarget = Number(rawVal);
2346
+ return !isNaN(nVal) && !isNaN(nTarget) ? nVal < nTarget : strVal < rawVal;
2347
+ }
2348
+ case "lte": {
2349
+ const nVal = Number(val);
2350
+ const nTarget = Number(rawVal);
2351
+ return !isNaN(nVal) && !isNaN(nTarget) ? nVal <= nTarget : strVal <= rawVal;
2352
+ }
2353
+ case "in": {
2354
+ const inner = rawVal.replace(/^\(|\)$/g, "");
2355
+ const items = inner.split(",").map((s) => s.trim());
2356
+ return items.includes(strVal);
2357
+ }
2358
+ default:
2359
+ return true;
2360
+ }
2361
+ }
2362
+
2363
+ class MemoryRealtimeTransport {
2364
+ subscribers = new Map;
2365
+ connected = true;
2366
+ connect() {
2367
+ this.connected = true;
2368
+ }
2369
+ disconnect() {
2370
+ this.connected = false;
2371
+ }
2372
+ isConnected() {
2373
+ return this.connected;
2374
+ }
2375
+ send(message) {
2376
+ if (!this.connected)
2377
+ return;
2378
+ const targets = this.subscribers.get(message.topic);
2379
+ if (!targets)
2380
+ return;
2381
+ for (const callback of targets) {
2382
+ try {
2383
+ callback(message);
2384
+ } catch {}
2385
+ }
2386
+ }
2387
+ subscribe(topic, onMessage) {
2388
+ let set = this.subscribers.get(topic);
2389
+ if (!set) {
2390
+ set = new Set;
2391
+ this.subscribers.set(topic, set);
2392
+ }
2393
+ set.add(onMessage);
2394
+ return () => {
2395
+ const current = this.subscribers.get(topic);
2396
+ if (current) {
2397
+ current.delete(onMessage);
2398
+ if (current.size === 0) {
2399
+ this.subscribers.delete(topic);
2400
+ }
2401
+ }
2402
+ };
2403
+ }
2404
+ clear() {
2405
+ this.subscribers.clear();
2406
+ }
2407
+ }
2408
+
2409
+ class SupaCloudRealtimeChannel {
2410
+ topic;
2411
+ config;
2412
+ transport;
2413
+ channelStatus = "CLOSED";
2414
+ statusCallbacks = [];
2415
+ postgresCallbacks = [];
2416
+ broadcastCallbacks = [];
2417
+ presenceCallbacks = [];
2418
+ presences = {};
2419
+ presenceKey;
2420
+ localPresenceRef;
2421
+ transportUnsubscribe = null;
2422
+ subscriptionTimer = null;
2423
+ constructor(topic, transport, config = {}) {
2424
+ this.topic = topic;
2425
+ this.transport = transport;
2426
+ this.config = config;
2427
+ this.presenceKey = config.presence?.key ?? (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function" ? crypto.randomUUID() : `sub_${Math.random().toString(36).substring(2, 10)}`);
2428
+ this.localPresenceRef = typeof crypto !== "undefined" && typeof crypto.randomUUID === "function" ? crypto.randomUUID() : `ref_${Math.random().toString(36).substring(2, 10)}`;
2429
+ }
2430
+ get state() {
2431
+ return this.channelStatus;
2432
+ }
2433
+ on(type, filter, callback) {
2434
+ if (type === "postgres_changes") {
2435
+ this.postgresCallbacks.push({
2436
+ filter,
2437
+ callback
2438
+ });
2439
+ } else if (type === "broadcast") {
2440
+ const evt = String(filter.event ?? "*");
2441
+ this.broadcastCallbacks.push({
2442
+ event: evt,
2443
+ callback
2444
+ });
2445
+ } else if (type === "presence") {
2446
+ const evt = filter.event ?? "sync";
2447
+ this.presenceCallbacks.push({
2448
+ event: evt,
2449
+ callback
2450
+ });
2451
+ }
2452
+ return this;
2453
+ }
2454
+ subscribe(callback, timeoutMs = 1e4) {
2455
+ if (callback) {
2456
+ this.statusCallbacks.push(callback);
2457
+ }
2458
+ if (this.channelStatus === "SUBSCRIBED") {
2459
+ if (callback)
2460
+ callback("SUBSCRIBED");
2461
+ return this;
2462
+ }
2463
+ if (this.transport.connect) {
2464
+ Promise.resolve(this.transport.connect()).catch((err) => {
2465
+ this.emitStatus("ERRORED", err instanceof Error ? err : new Error(String(err)));
2466
+ });
2467
+ }
2468
+ if (timeoutMs > 0) {
2469
+ this.subscriptionTimer = setTimeout(() => {
2470
+ if (this.channelStatus !== "SUBSCRIBED" && this.channelStatus !== "CLOSED") {
2471
+ this.emitStatus("TIMED_OUT", new Error(`Subscription timed out after ${timeoutMs}ms`));
2472
+ }
2473
+ }, timeoutMs);
2474
+ }
2475
+ this.transportUnsubscribe = this.transport.subscribe(this.topic, (message) => {
2476
+ this.handleIncomingMessage(message);
2477
+ });
2478
+ if (this.subscriptionTimer) {
2479
+ clearTimeout(this.subscriptionTimer);
2480
+ this.subscriptionTimer = null;
2481
+ }
2482
+ this.emitStatus("SUBSCRIBED");
2483
+ return this;
2484
+ }
2485
+ async unsubscribe() {
2486
+ if (this.subscriptionTimer) {
2487
+ clearTimeout(this.subscriptionTimer);
2488
+ this.subscriptionTimer = null;
2489
+ }
2490
+ if (this.transportUnsubscribe) {
2491
+ this.transportUnsubscribe();
2492
+ this.transportUnsubscribe = null;
2493
+ }
2494
+ await this.untrack();
2495
+ this.emitStatus("CLOSED");
2496
+ return "ok";
2497
+ }
2498
+ async send(args) {
2499
+ if (this.channelStatus === "CLOSED") {
2500
+ return "error";
2501
+ }
2502
+ const message = {
2503
+ topic: this.topic,
2504
+ event: "broadcast",
2505
+ payload: {
2506
+ type: "broadcast",
2507
+ event: args.event,
2508
+ payload: args.payload,
2509
+ __sender: this.localPresenceRef
2510
+ }
2511
+ };
2512
+ try {
2513
+ await this.transport.send(message);
2514
+ return "ok";
2515
+ } catch {
2516
+ return "error";
2517
+ }
2518
+ }
2519
+ async track(payload) {
2520
+ if (this.channelStatus === "CLOSED")
2521
+ return "error";
2522
+ const entry = {
2523
+ presence_ref: this.localPresenceRef,
2524
+ ...payload
2525
+ };
2526
+ const message = {
2527
+ topic: this.topic,
2528
+ event: "presence_join",
2529
+ payload: {
2530
+ key: this.presenceKey,
2531
+ current: [entry]
2532
+ }
2533
+ };
2534
+ try {
2535
+ await this.transport.send(message);
2536
+ const prev = this.presences[this.presenceKey] ?? [];
2537
+ const updated = [
2538
+ ...prev.filter((p) => p.presence_ref !== this.localPresenceRef),
2539
+ entry
2540
+ ];
2541
+ this.presences[this.presenceKey] = updated;
2542
+ this.dispatchPresence("join", {
2543
+ key: this.presenceKey,
2544
+ currentPresences: updated,
2545
+ newPresences: [entry]
2546
+ });
2547
+ this.dispatchPresence("sync", this.presences);
2548
+ return "ok";
2549
+ } catch {
2550
+ return "error";
2551
+ }
2552
+ }
2553
+ async untrack() {
2554
+ const prev = this.presences[this.presenceKey];
2555
+ if (!prev || prev.length === 0)
2556
+ return "ok";
2557
+ const left = prev.filter((p) => p.presence_ref === this.localPresenceRef);
2558
+ if (left.length === 0)
2559
+ return "ok";
2560
+ const remaining = prev.filter((p) => p.presence_ref !== this.localPresenceRef);
2561
+ if (remaining.length === 0) {
2562
+ delete this.presences[this.presenceKey];
2563
+ } else {
2564
+ this.presences[this.presenceKey] = remaining;
2565
+ }
2566
+ const message = {
2567
+ topic: this.topic,
2568
+ event: "presence_leave",
2569
+ payload: {
2570
+ key: this.presenceKey,
2571
+ left
2572
+ }
2573
+ };
2574
+ try {
2575
+ await this.transport.send(message);
2576
+ } catch {}
2577
+ this.dispatchPresence("leave", {
2578
+ key: this.presenceKey,
2579
+ currentPresences: remaining,
2580
+ leftPresences: left
2581
+ });
2582
+ this.dispatchPresence("sync", this.presences);
2583
+ return "ok";
2584
+ }
2585
+ presenceState() {
2586
+ return this.presences;
2587
+ }
2588
+ emitStatus(status, err) {
2589
+ this.channelStatus = status;
2590
+ for (const cb of this.statusCallbacks) {
2591
+ try {
2592
+ cb(status, err);
2593
+ } catch {}
2594
+ }
2595
+ }
2596
+ handleIncomingMessage(message) {
2597
+ const { event, payload } = message;
2598
+ if (event === "postgres_changes") {
2599
+ this.dispatchPostgresChange(payload);
2600
+ } else if (event === "broadcast") {
2601
+ const sender = payload.__sender;
2602
+ if (sender === this.localPresenceRef && !this.config.broadcast?.self) {
2603
+ return;
2604
+ }
2605
+ const bPayload = payload.payload !== undefined ? payload.payload : payload;
2606
+ const bEvent = String(payload.event ?? "*");
2607
+ this.dispatchBroadcast(bEvent, bPayload);
2608
+ } else if (event === "presence_join") {
2609
+ const key = String(payload.key ?? "");
2610
+ const incoming = payload.current ?? [];
2611
+ const prev = this.presences[key] ?? [];
2612
+ const updated = [
2613
+ ...prev.filter((p) => !incoming.some((i) => i.presence_ref === p.presence_ref)),
2614
+ ...incoming
2615
+ ];
2616
+ this.presences[key] = updated;
2617
+ this.dispatchPresence("join", {
2618
+ key,
2619
+ currentPresences: updated,
2620
+ newPresences: incoming
2621
+ });
2622
+ this.dispatchPresence("sync", this.presences);
2623
+ } else if (event === "presence_leave") {
2624
+ const key = String(payload.key ?? "");
2625
+ const left = payload.left ?? [];
2626
+ const prev = this.presences[key] ?? [];
2627
+ const remaining = prev.filter((p) => !left.some((l) => l.presence_ref === p.presence_ref));
2628
+ if (remaining.length === 0) {
2629
+ delete this.presences[key];
2630
+ } else {
2631
+ this.presences[key] = remaining;
2632
+ }
2633
+ this.dispatchPresence("leave", {
2634
+ key,
2635
+ currentPresences: remaining,
2636
+ leftPresences: left
2637
+ });
2638
+ this.dispatchPresence("sync", this.presences);
2639
+ }
2640
+ }
2641
+ dispatchPostgresChange(payload) {
2642
+ if (!payload || !payload.schema || !payload.table || !payload.eventType)
2643
+ return;
2644
+ for (const { filter, callback } of this.postgresCallbacks) {
2645
+ if (filter.schema !== "*" && filter.schema.toLowerCase() !== payload.schema.toLowerCase()) {
2646
+ continue;
2647
+ }
2648
+ if (filter.table && filter.table !== "*" && filter.table.toLowerCase() !== payload.table.toLowerCase()) {
2649
+ continue;
2650
+ }
2651
+ if (filter.event !== "*" && filter.event.toUpperCase() !== payload.eventType.toUpperCase()) {
2652
+ continue;
2653
+ }
2654
+ const recordToMatch = payload.eventType === "DELETE" ? payload.old : payload.new;
2655
+ if (recordToMatch && !matchesPostgresFilter(filter.filter, recordToMatch)) {
2656
+ continue;
2657
+ }
2658
+ try {
2659
+ callback(payload);
2660
+ } catch {}
2661
+ }
2662
+ }
2663
+ dispatchBroadcast(event, payload) {
2664
+ for (const listener of this.broadcastCallbacks) {
2665
+ if (listener.event === "*" || listener.event === event) {
2666
+ try {
2667
+ listener.callback({
2668
+ type: "broadcast",
2669
+ event,
2670
+ payload
2671
+ });
2672
+ } catch {}
2673
+ }
2674
+ }
2675
+ }
2676
+ dispatchPresence(event, payload) {
2677
+ for (const listener of this.presenceCallbacks) {
2678
+ if (listener.event === event) {
2679
+ try {
2680
+ listener.callback(payload);
2681
+ } catch {}
2682
+ }
2683
+ }
2684
+ }
2685
+ }
2686
+ function createRealtimeAdapter(options = {}) {
2687
+ const transport = options.transport ?? new MemoryRealtimeTransport;
2688
+ return {
2689
+ channel(topic, config) {
2690
+ return new SupaCloudRealtimeChannel(topic, transport, config);
2691
+ },
2692
+ get transport() {
2693
+ return transport;
2694
+ }
2695
+ };
2696
+ }
2697
+
2312
2698
  // node_modules/@supacloud/query/dist/index.js
2313
2699
  async function invalidateByTags(queryClient, tags, keyPrefix) {
2314
2700
  const targetTags = Array.isArray(tags) ? tags : [tags];
@@ -3679,9 +4065,9 @@ function captureTaskSubscribeOptions(options) {
3679
4065
  if (typeof captured.onUpdate !== "function" || captured.onStateChange !== undefined && typeof captured.onStateChange !== "function" || captured.onError !== undefined && typeof captured.onError !== "function" || captured.stopOnTerminal !== undefined && typeof captured.stopOnTerminal !== "boolean") {
3680
4066
  throw new Error("Invalid task subscription options");
3681
4067
  }
3682
- const realtime = captureTaskRealtimeSource(captured.realtime);
3683
- if (realtime)
3684
- captured.realtime = realtime;
4068
+ const realtime2 = captureTaskRealtimeSource(captured.realtime);
4069
+ if (realtime2)
4070
+ captured.realtime = realtime2;
3685
4071
  return captured;
3686
4072
  }
3687
4073
  function normalizeTaskSnapshot(task, taskId, projectRef, decoder) {
@@ -3999,7 +4385,7 @@ class SupaCloudTasksClient extends SupaCloudManagementClient {
3999
4385
  subscribeInternal(taskId, options, decoder) {
4000
4386
  taskId = captureTaskId(taskId);
4001
4387
  options = captureTaskSubscribeOptions(options);
4002
- const realtime = captureTaskRealtimeSource(options.realtime);
4388
+ const realtime2 = captureTaskRealtimeSource(options.realtime);
4003
4389
  const projectRef = this.options.projectRef;
4004
4390
  let closed = false;
4005
4391
  let channel = null;
@@ -4156,14 +4542,14 @@ class SupaCloudTasksClient extends SupaCloudManagementClient {
4156
4542
  close();
4157
4543
  }
4158
4544
  };
4159
- if (!realtime) {
4545
+ if (!realtime2) {
4160
4546
  startPolling();
4161
4547
  return subscription;
4162
4548
  }
4163
4549
  channel = this.options.supabase.channel(`supacloud-task:${this.options.projectRef}:${taskId}`).on("postgres_changes", {
4164
4550
  event: "*",
4165
- schema: realtime.schema,
4166
- table: realtime.table,
4551
+ schema: realtime2.schema,
4552
+ table: realtime2.table,
4167
4553
  filter: `id=eq.${taskId}`
4168
4554
  }, (payload) => {
4169
4555
  const next = payload.new && Object.keys(payload.new).length > 0 ? payload.new : payload.old;
@@ -4389,11 +4775,22 @@ class SupaCloudQueuesClient extends SupaCloudManagementClient {
4389
4775
  await this.request(`/v1/projects/${this.options.projectRef}/tasks/queues/${encodeURIComponent(queueName)}`, "DELETE", undefined, decodeVoid);
4390
4776
  }
4391
4777
  }
4778
+ function openSupabaseChannel(supabase, topic, config) {
4779
+ if (!config)
4780
+ return supabase.channel(topic);
4781
+ return supabase.channel(topic, {
4782
+ config: {
4783
+ ...config.broadcast ? { broadcast: config.broadcast } : {},
4784
+ ...config.presence ? { presence: config.presence } : {}
4785
+ }
4786
+ });
4787
+ }
4392
4788
  function createSupaCloudClient(options) {
4393
4789
  const normalized = {
4394
4790
  ...options,
4395
4791
  managementApiUrl: normalizeBaseUrl(options.managementApiUrl),
4396
4792
  pollingIntervalMs: options.pollingIntervalMs ?? 3000,
4793
+ realtimeTransport: options.realtimeTransport ?? null,
4397
4794
  getAccessToken: options.getAccessToken ?? (() => defaultAccessTokenResolver(options.supabase))
4398
4795
  };
4399
4796
  const tasks = new SupaCloudTasksClient(normalized);
@@ -4403,6 +4800,10 @@ function createSupaCloudClient(options) {
4403
4800
  const workflows2 = new SupaCloudWorkflowsClient(options.supabase);
4404
4801
  const commands2 = new SupaCloudCommandsClient(options.supabase);
4405
4802
  const artifacts2 = new SupaCloudArtifactsClient(options.supabase);
4803
+ const realtime2 = createRealtimeAdapter({
4804
+ transport: options.realtimeTransport ?? undefined,
4805
+ projectRef: normalized.projectRef
4806
+ });
4406
4807
  const instance = {
4407
4808
  supabase: options.supabase,
4408
4809
  projectRef: normalized.projectRef,
@@ -4416,6 +4817,8 @@ function createSupaCloudClient(options) {
4416
4817
  commands: commands2,
4417
4818
  artifacts: artifacts2,
4418
4819
  queues,
4820
+ realtime: realtime2,
4821
+ channel: (topic, config) => options.realtimeTransport ? realtime2.channel(topic, config) : openSupabaseChannel(options.supabase, topic, config),
4419
4822
  queue: (name) => new SupaCloudQueueClient(normalized, name),
4420
4823
  functions: {
4421
4824
  invokeBackground: (functionName, submitOptions) => tasks.submit(functionName, submitOptions)
@@ -4441,6 +4844,7 @@ function createSupaCloudClient(options) {
4441
4844
  };
4442
4845
  }
4443
4846
  export {
4847
+ MemoryRealtimeTransport,
4444
4848
  SupaCloudApiError,
4445
4849
  SupaCloudArtifactLinkError,
4446
4850
  SupaCloudArtifactReadError,
@@ -4455,6 +4859,7 @@ export {
4455
4859
  SupaCloudOAuthServerError,
4456
4860
  SupaCloudProcedureError,
4457
4861
  SupaCloudQueueError,
4862
+ SupaCloudRealtimeChannel,
4458
4863
  SupaCloudTaskAuthenticationError,
4459
4864
  SupaCloudTaskDecoderError as SupaCloudTaskDecodeError,
4460
4865
  SupaCloudTaskDecoderError,
@@ -4475,6 +4880,7 @@ export {
4475
4880
  createProcedureClient,
4476
4881
  createQueryAdapter,
4477
4882
  createQueryKey,
4883
+ createRealtimeAdapter,
4478
4884
  createSupaCloudApiFetch,
4479
4885
  createSupaCloudArtifactFetch,
4480
4886
  createSupaCloudClient,
@@ -4490,5 +4896,6 @@ export {
4490
4896
  isSupaCloudProcedureError,
4491
4897
  isSupaCloudProcedureErrorCode,
4492
4898
  isSupaCloudProcedureHttpError,
4493
- isSupaCloudProcedureTransportError
4899
+ isSupaCloudProcedureTransportError,
4900
+ matchesPostgresFilter
4494
4901
  };