lazypock 0.17.1 → 0.19.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.cjs CHANGED
@@ -41,7 +41,7 @@ __export(index_exports, {
41
41
  getThumbUrl: () => getThumbUrl,
42
42
  getVariantUrl: () => getVariantUrl,
43
43
  schemaFieldType: () => schemaFieldType,
44
- wsUrlFromBaseUrl: () => wsUrlFromBaseUrl
44
+ sseUrlFromBaseUrl: () => sseUrlFromBaseUrl
45
45
  });
46
46
  module.exports = __toCommonJS(index_exports);
47
47
 
@@ -97,7 +97,7 @@ var HttpClient = class {
97
97
  const collection = this.authStore.collectionName;
98
98
  if (!collection) return null;
99
99
  try {
100
- const url = this.baseUrl + "/" + encodeURIComponent(collection) + "/auth-refresh";
100
+ const url = this.baseUrl + "/collections/" + encodeURIComponent(collection) + "/auth-refresh";
101
101
  const headers = {
102
102
  "Content-Type": "application/json"
103
103
  };
@@ -880,6 +880,19 @@ var CollectionService = class _CollectionService {
880
880
  encodeId(id) {
881
881
  return encodeURIComponent(id);
882
882
  }
883
+ /**
884
+ * The records endpoint for this collection.
885
+ *
886
+ * Centralised because the server's shape is `/api/collections/<name>/records`,
887
+ * and a path repeated eighteen times is a path that drifts.
888
+ */
889
+ recordsPath() {
890
+ return "/collections/" + this.encodeId(this.collectionName) + "/records";
891
+ }
892
+ /** The collection's own endpoint, which is where its auth routes live. */
893
+ collectionPath() {
894
+ return "/collections/" + this.encodeId(this.collectionName);
895
+ }
883
896
  // ── Field projection (`.select`) ──
884
897
  /**
885
898
  * Project list/read responses to the given fields (PocketBase `fields`
@@ -1287,7 +1300,7 @@ var CollectionService = class _CollectionService {
1287
1300
  }).map(([k, v]) => [k, String(v)])
1288
1301
  )
1289
1302
  ).toString();
1290
- const result = await this.http.get("/" + this.encodeId(this.collectionName) + "?" + qs, {
1303
+ const result = await this.http.get(this.recordsPath() + "?" + qs, {
1291
1304
  requestKey,
1292
1305
  autoCancel,
1293
1306
  cancelKey,
@@ -1372,7 +1385,7 @@ var CollectionService = class _CollectionService {
1372
1385
  }
1373
1386
  const qsStr = qs.toString();
1374
1387
  const record = await this.http.get(
1375
- "/" + this.encodeId(this.collectionName) + "/" + this.encodeId(id) + (qsStr ? "?" + qsStr : ""),
1388
+ this.recordsPath() + "/" + this.encodeId(id) + (qsStr ? "?" + qsStr : ""),
1376
1389
  options
1377
1390
  );
1378
1391
  if (record && expandInfo.narrow.size > 0) {
@@ -1388,7 +1401,7 @@ var CollectionService = class _CollectionService {
1388
1401
  */
1389
1402
  create(data, options) {
1390
1403
  return this.http.post(
1391
- "/" + this.encodeId(this.collectionName),
1404
+ this.recordsPath(),
1392
1405
  data,
1393
1406
  options
1394
1407
  );
@@ -1402,7 +1415,7 @@ var CollectionService = class _CollectionService {
1402
1415
  */
1403
1416
  update(id, data, options) {
1404
1417
  return this.http.patch(
1405
- "/" + this.encodeId(this.collectionName) + "/" + this.encodeId(id),
1418
+ this.recordsPath() + "/" + this.encodeId(id),
1406
1419
  data,
1407
1420
  options
1408
1421
  );
@@ -1414,7 +1427,7 @@ var CollectionService = class _CollectionService {
1414
1427
  */
1415
1428
  delete(id, options) {
1416
1429
  return this.http.delete(
1417
- "/" + this.encodeId(this.collectionName) + "/" + this.encodeId(id),
1430
+ this.recordsPath() + "/" + this.encodeId(id),
1418
1431
  options
1419
1432
  );
1420
1433
  }
@@ -1522,7 +1535,7 @@ var CollectionService = class _CollectionService {
1522
1535
  */
1523
1536
  async authWithPassword(identity, password, options) {
1524
1537
  const data = await this.http.post(
1525
- "/" + this.encodeId(this.collectionName) + "/auth-with-password",
1538
+ this.collectionPath() + "/auth-with-password",
1526
1539
  { identity, password },
1527
1540
  options
1528
1541
  );
@@ -1538,7 +1551,7 @@ var CollectionService = class _CollectionService {
1538
1551
  */
1539
1552
  async authRefresh(options) {
1540
1553
  const data = await this.http.post(
1541
- "/" + this.encodeId(this.collectionName) + "/auth-refresh",
1554
+ this.collectionPath() + "/auth-refresh",
1542
1555
  void 0,
1543
1556
  options
1544
1557
  );
@@ -1555,7 +1568,7 @@ var CollectionService = class _CollectionService {
1555
1568
  */
1556
1569
  async listAuthMethods(options) {
1557
1570
  return this.http.get(
1558
- "/" + this.encodeId(this.collectionName) + "/auth-methods",
1571
+ this.collectionPath() + "/auth-methods",
1559
1572
  options
1560
1573
  );
1561
1574
  }
@@ -1574,7 +1587,7 @@ var CollectionService = class _CollectionService {
1574
1587
  */
1575
1588
  async requestPasswordReset(email, options) {
1576
1589
  await this.http.post(
1577
- "/" + this.encodeId(this.collectionName) + "/request-password-reset",
1590
+ this.collectionPath() + "/request-password-reset",
1578
1591
  { email },
1579
1592
  options
1580
1593
  );
@@ -1589,7 +1602,7 @@ var CollectionService = class _CollectionService {
1589
1602
  */
1590
1603
  async confirmPasswordReset(passwordResetToken, password, passwordConfirm, options) {
1591
1604
  await this.http.post(
1592
- "/" + this.encodeId(this.collectionName) + "/confirm-password-reset",
1605
+ this.collectionPath() + "/confirm-password-reset",
1593
1606
  { token: passwordResetToken, password, passwordConfirm },
1594
1607
  options
1595
1608
  );
@@ -1602,7 +1615,7 @@ var CollectionService = class _CollectionService {
1602
1615
  */
1603
1616
  async requestVerification(email, options) {
1604
1617
  await this.http.post(
1605
- "/" + this.encodeId(this.collectionName) + "/request-verification",
1618
+ this.collectionPath() + "/request-verification",
1606
1619
  { email },
1607
1620
  options
1608
1621
  );
@@ -1614,7 +1627,7 @@ var CollectionService = class _CollectionService {
1614
1627
  */
1615
1628
  async confirmVerification(verificationToken, options) {
1616
1629
  const data = await this.http.post(
1617
- "/" + this.encodeId(this.collectionName) + "/confirm-verification",
1630
+ this.collectionPath() + "/confirm-verification",
1618
1631
  { token: verificationToken },
1619
1632
  options
1620
1633
  );
@@ -1626,7 +1639,7 @@ var CollectionService = class _CollectionService {
1626
1639
  */
1627
1640
  async requestEmailChange(newEmail, options) {
1628
1641
  await this.http.post(
1629
- "/" + this.encodeId(this.collectionName) + "/request-email-change",
1642
+ this.collectionPath() + "/request-email-change",
1630
1643
  { newEmail },
1631
1644
  options
1632
1645
  );
@@ -1639,7 +1652,7 @@ var CollectionService = class _CollectionService {
1639
1652
  */
1640
1653
  async confirmEmailChange(emailChangeToken, password, options) {
1641
1654
  const data = await this.http.post(
1642
- "/" + this.encodeId(this.collectionName) + "/confirm-email-change",
1655
+ this.collectionPath() + "/confirm-email-change",
1643
1656
  { token: emailChangeToken, password },
1644
1657
  options
1645
1658
  );
@@ -1707,7 +1720,7 @@ var CollectionService = class _CollectionService {
1707
1720
  async authWithOAuth2Code(options) {
1708
1721
  const { provider, code, codeVerifier, redirectUrl, createData } = options;
1709
1722
  const data = await this.http.post(
1710
- "/" + this.encodeId(this.collectionName) + "/auth-with-oauth2",
1723
+ this.collectionPath() + "/auth-with-oauth2",
1711
1724
  {
1712
1725
  provider,
1713
1726
  code,
@@ -1734,259 +1747,245 @@ var CollectionService = class _CollectionService {
1734
1747
  };
1735
1748
 
1736
1749
  // src/realtime.ts
1737
- function wsUrlFromBaseUrl(baseUrl) {
1738
- try {
1739
- const url = new URL(baseUrl);
1740
- const protocol = url.protocol === "https:" ? "wss:" : "ws:";
1741
- return `${protocol}//${url.host}/socket/websocket`;
1742
- } catch {
1743
- return `${baseUrl.replace(/^http/, "ws").replace(/\/api$/, "")}/socket/websocket`;
1744
- }
1750
+ function sseUrlFromBaseUrl(baseUrl) {
1751
+ return `${baseUrl.replace(/\/+$/, "")}/realtime`;
1752
+ }
1753
+ function serverTopic(topic) {
1754
+ if (topic === "collections") return "collections";
1755
+ if (!topic.startsWith("collection:")) return null;
1756
+ const rest = topic.slice("collection:".length);
1757
+ const [name, recordId] = rest.split(":");
1758
+ if (!name) return null;
1759
+ return recordId ? `${name}/${recordId}` : name;
1745
1760
  }
1746
1761
  var RealtimeService = class {
1747
1762
  constructor() {
1748
- this.ws = null;
1749
- this.refCounter = 0;
1763
+ this.controller = null;
1764
+ this.open = false;
1765
+ this.closed = false;
1750
1766
  this.subscriptions = /* @__PURE__ */ new Map();
1751
1767
  this.reconnectTimer = null;
1768
+ this.resubscribeTimer = null;
1752
1769
  this.reconnectAttempt = 0;
1753
1770
  this.maxReconnectDelay = 5e3;
1754
1771
  this.url = "";
1755
1772
  this.tokenProvider = null;
1756
- // ── Heartbeat ──
1757
- this.heartbeatInterval = null;
1758
1773
  }
1759
- /** Whether the WebSocket is currently open. */
1774
+ /** Whether the stream is currently open. */
1760
1775
  get isOpen() {
1761
- return this.ws?.readyState === WebSocket.OPEN;
1776
+ return this.open;
1762
1777
  }
1763
- /**
1764
- * The most recently used WebSocket URL (set on {@link connect}).
1765
- * Useful for SDK convenience methods that auto-connect before subscribing.
1766
- */
1778
+ /** The most recently used SSE URL (set on {@link connect}/{@link setUrl}). */
1767
1779
  get lastUrl() {
1768
1780
  return this.url;
1769
1781
  }
1770
- /** The auth token configured for this connection (set on connect). */
1782
+ /** The auth token configured for this connection. */
1771
1783
  get lastToken() {
1772
1784
  return this.token;
1773
1785
  }
1774
- /**
1775
- * Set the per-client connection id (browser tab / device). The SDK
1776
- * appends it as the `connectionId` socket query param at connect time
1777
- * (unless the URL already carries one), matching the `X-Connection-Id`
1778
- * header the HTTP client sends — together they let the server exclude
1779
- * the originating connection from its own realtime broadcasts.
1780
- */
1786
+ /** Set the per-client connection id (browser tab / device). */
1781
1787
  setConnectionId(id) {
1782
1788
  this.connectionId = id;
1783
1789
  }
1784
- /**
1785
- * Set the socket URL. Useful before subscribing so the SDK can
1786
- * auto-connect on the first {@link subscribe}.
1787
- */
1790
+ /** Set the stream URL. Useful before subscribing so the SDK auto-connects. */
1788
1791
  setUrl(url) {
1789
1792
  this.url = url;
1790
1793
  }
1791
- /**
1792
- * Register a token provider consulted at every (re)connect.
1793
- * When set, it takes precedence over the token passed to {@link connect}.
1794
- */
1794
+ /** Register a token provider consulted at every (re)connect. */
1795
1795
  setTokenProvider(provider) {
1796
1796
  this.tokenProvider = provider;
1797
1797
  }
1798
1798
  /**
1799
- * Reconnect the socket immediately with the current token.
1800
- * Called by the SDK when auth changes (login/logout/token refresh) so
1801
- * private-channel joins are authorized with the new credentials. No-op
1802
- * when the socket has never been opened and nothing is subscribed.
1799
+ * Reconnect immediately with the current token, so auth changes
1800
+ * (login/logout/refresh) re-authorize private subscriptions.
1803
1801
  */
1804
1802
  refresh() {
1805
- if (typeof WebSocket === "undefined") return;
1806
- if (!this.ws && this.subscriptions.size === 0) return;
1807
- this.clearReconnectTimer();
1808
- const ws = this.ws;
1809
- this.ws = null;
1810
- if (ws) {
1811
- ws.onclose = null;
1812
- ws.close();
1813
- }
1803
+ if (this.closed) return;
1804
+ if (!this.open && this.subscriptions.size === 0) return;
1814
1805
  this.reconnectAttempt = 0;
1815
1806
  this.doConnect();
1816
1807
  }
1817
- /*
1818
- * Ensure the socket is connected, then subscribe.
1819
- * Used by collection-level convenience wrappers so a connection is opened
1820
- * automatically on the first subscribe (matching PocketBase behaviour —
1821
- * works for anonymous/public collections too).
1822
- */
1808
+ /** Ensure a connection is open, then subscribe. */
1823
1809
  ensureConnected() {
1824
- if (this.isOpen || !this.url) return;
1825
- if (typeof WebSocket === "undefined") return;
1810
+ if (this.open || this.controller || !this.url) return;
1811
+ if (this.serverTopics().length === 0) return;
1826
1812
  this.doConnect();
1827
1813
  }
1828
1814
  connect(opts) {
1829
1815
  this.url = opts.url;
1830
1816
  this.token = opts.token;
1817
+ this.closed = false;
1831
1818
  this.reconnectAttempt = 0;
1832
1819
  this.doConnect();
1833
1820
  }
1834
1821
  disconnect() {
1822
+ this.closed = true;
1835
1823
  this.clearReconnectTimer();
1836
- this.ws?.close();
1837
- this.ws = null;
1824
+ this.closeStream();
1838
1825
  }
1839
1826
  /**
1840
- * Subscribe to a topic (e.g. "collection:posts" or "custom:chat-room").
1841
- * The backend Channel authorizes via listRule on join.
1842
- *
1843
- * @param joinPayload Optional payload forwarded with the channel join
1844
- * (available to the server's join callback / hooks, e.g. `expand`).
1827
+ * Subscribe to a topic (`collection:posts`, `collection:posts:ID`, or the
1828
+ * registry topic `collections`).
1845
1829
  */
1846
1830
  subscribe(topic, callback, joinPayload) {
1847
1831
  const subs = this.subscriptions.get(topic) || [];
1848
1832
  subs.push({ topic, callback, joinPayload });
1849
1833
  this.subscriptions.set(topic, subs);
1850
- if (this.ws?.readyState === WebSocket.OPEN) {
1851
- this.joinTopic(topic, joinPayload);
1852
- }
1834
+ this.resubscribe();
1853
1835
  }
1854
- /**
1855
- * Remove all subscriptions for topics under `prefix` (the topic itself or
1856
- * any topic starting with `prefix + ":"`). Used by collection-level
1857
- * `unsubscribe()` to drop every subscription of a collection.
1858
- */
1836
+ /** Remove every subscription under `prefix` (the topic or `prefix:...`). */
1859
1837
  unsubscribeByPrefix(prefix) {
1838
+ let changed = false;
1860
1839
  for (const topic of [...this.subscriptions.keys()]) {
1861
1840
  if (topic === prefix || topic.startsWith(prefix + ":")) {
1862
1841
  this.subscriptions.delete(topic);
1842
+ changed = true;
1863
1843
  }
1864
1844
  }
1845
+ if (changed) this.resubscribe();
1865
1846
  }
1866
- /**
1867
- * Unsubscribe a specific callback from a topic.
1868
- */
1847
+ /** Remove a specific callback from a topic, or the whole topic. */
1869
1848
  unsubscribe(topic, callback) {
1870
1849
  if (!callback) {
1871
- this.subscriptions.delete(topic);
1850
+ if (this.subscriptions.delete(topic)) this.resubscribe();
1872
1851
  return;
1873
1852
  }
1874
1853
  const subs = this.subscriptions.get(topic)?.filter((s) => s.callback !== callback);
1875
1854
  if (subs && subs.length > 0) {
1876
1855
  this.subscriptions.set(topic, subs);
1877
- } else {
1878
- this.subscriptions.delete(topic);
1856
+ return;
1879
1857
  }
1858
+ this.subscriptions.delete(topic);
1859
+ this.resubscribe();
1880
1860
  }
1881
- resubscribeAll() {
1882
- const seen = /* @__PURE__ */ new Set();
1883
- for (const entries of this.subscriptions.values()) {
1884
- for (const entry of entries) {
1885
- if (seen.has(entry.topic)) continue;
1886
- seen.add(entry.topic);
1887
- if (this.ws?.readyState === WebSocket.OPEN) {
1888
- this.joinTopic(entry.topic, entry.joinPayload);
1889
- }
1890
- }
1861
+ // ── Internals ────────────────────────────────────
1862
+ /** The distinct server topics the current subscriptions need. */
1863
+ serverTopics() {
1864
+ const topics = /* @__PURE__ */ new Set();
1865
+ for (const topic of this.subscriptions.keys()) {
1866
+ const server = serverTopic(topic);
1867
+ if (server) topics.add(server);
1891
1868
  }
1869
+ return [...topics];
1870
+ }
1871
+ /**
1872
+ * The subscription set is part of the connection URL, so a change needs a new
1873
+ * connection. Coalesced, because mounting a page subscribes to several
1874
+ * collections in one tick.
1875
+ */
1876
+ resubscribe() {
1877
+ if (this.resubscribeTimer) clearTimeout(this.resubscribeTimer);
1878
+ this.resubscribeTimer = setTimeout(() => {
1879
+ this.resubscribeTimer = null;
1880
+ if (this.controller) {
1881
+ this.doConnect();
1882
+ } else {
1883
+ this.ensureConnected();
1884
+ }
1885
+ }, 0);
1892
1886
  }
1893
1887
  doConnect() {
1894
- if (typeof WebSocket === "undefined") {
1895
- console.warn(
1896
- "[lazypock] WebSocket not available \u2014 realtime subscriptions disabled"
1897
- );
1898
- return;
1899
- }
1900
- let url = this.url;
1888
+ if (this.closed) return;
1889
+ const topics = this.serverTopics();
1890
+ if (topics.length === 0 || !this.url) return;
1891
+ this.closeStream();
1892
+ const params = new URLSearchParams();
1893
+ params.set("subscribe", topics.join(","));
1894
+ const url = this.url + (this.url.includes("?") ? "&" : "?") + params.toString();
1901
1895
  const token = this.tokenProvider ? this.tokenProvider() : this.token;
1902
- if (token) {
1903
- url += (url.includes("?") ? "&" : "?") + "token=" + encodeURIComponent(token);
1904
- }
1905
- if (this.connectionId && !url.includes("connectionId=")) {
1906
- url += (url.includes("?") ? "&" : "?") + "connectionId=" + encodeURIComponent(this.connectionId);
1907
- }
1908
- this.ws = new WebSocket(url);
1909
- this.ws.onopen = () => {
1896
+ const headers = { Accept: "text/event-stream" };
1897
+ if (token) headers.Authorization = `Bearer ${token}`;
1898
+ if (this.connectionId) headers["X-Connection-Id"] = this.connectionId;
1899
+ const controller = new AbortController();
1900
+ this.controller = controller;
1901
+ void this.read(url, headers, controller);
1902
+ }
1903
+ async read(url, headers, controller) {
1904
+ try {
1905
+ const response = await fetch(url, { headers, signal: controller.signal });
1906
+ if (!response.ok || !response.body) {
1907
+ throw new Error(`realtime connection failed (${response.status})`);
1908
+ }
1909
+ this.open = true;
1910
1910
  this.reconnectAttempt = 0;
1911
- this.resubscribeAll();
1912
- this.startHeartbeat();
1913
- };
1914
- this.ws.onmessage = (msg) => {
1915
- this.handleMessage(msg.data);
1916
- };
1917
- this.ws.onclose = () => {
1918
- this.stopHeartbeat();
1919
- this.onDisconnect?.();
1920
- this.scheduleReconnect();
1921
- };
1922
- this.ws.onerror = (err) => {
1911
+ this.onReconnect?.();
1912
+ const reader = response.body.getReader();
1913
+ const decoder = new TextDecoder();
1914
+ let buffer = "";
1915
+ for (; ; ) {
1916
+ const { done, value } = await reader.read();
1917
+ if (done) break;
1918
+ buffer = (buffer + decoder.decode(value, { stream: true })).replace(
1919
+ /\r\n/g,
1920
+ "\n"
1921
+ );
1922
+ let index;
1923
+ while ((index = buffer.indexOf("\n\n")) >= 0) {
1924
+ this.handleFrame(buffer.slice(0, index));
1925
+ buffer = buffer.slice(index + 2);
1926
+ }
1927
+ }
1928
+ throw new Error("realtime stream ended");
1929
+ } catch (err) {
1930
+ if (controller.signal.aborted) return;
1923
1931
  this.onError?.(err);
1924
- };
1932
+ } finally {
1933
+ if (this.controller === controller) {
1934
+ this.open = false;
1935
+ this.controller = null;
1936
+ this.onDisconnect?.();
1937
+ this.scheduleReconnect();
1938
+ }
1939
+ }
1925
1940
  }
1926
- handleMessage(data) {
1927
- let parsed;
1941
+ handleFrame(frame) {
1942
+ const dataLines = [];
1943
+ for (const line of frame.split("\n")) {
1944
+ if (line.startsWith("data:")) {
1945
+ dataLines.push(line.slice(5).replace(/^ /, ""));
1946
+ }
1947
+ }
1948
+ if (dataLines.length === 0) return;
1949
+ let data;
1928
1950
  try {
1929
- parsed = JSON.parse(data);
1951
+ data = JSON.parse(dataLines.join("\n"));
1930
1952
  } catch {
1931
1953
  return;
1932
1954
  }
1933
- if (typeof parsed !== "object" || !parsed.topic || !parsed.event) return;
1934
- const topic = parsed.topic;
1935
- const event = parsed.event;
1936
- const payload = parsed.payload || {};
1937
- if (event === "phx_reply") return;
1938
- const subs = this.subscriptions.get(topic);
1939
- if (subs) {
1940
- const e = {
1941
- event,
1942
- topic,
1943
- payload
1944
- };
1945
- for (const s of subs) {
1946
- try {
1947
- s.callback(e);
1948
- } catch {
1949
- }
1950
- }
1955
+ this.dispatch(data);
1956
+ }
1957
+ dispatch(data) {
1958
+ const action = typeof data.action === "string" ? data.action : "update";
1959
+ if (data.collection === "collections") {
1960
+ this.emit("collections", action, data.record ?? {});
1961
+ return;
1962
+ }
1963
+ if (!data.collection) return;
1964
+ const payload = { record: data.record ?? {}, action };
1965
+ this.emit(`collection:${data.collection}`, action, payload);
1966
+ if (data.id) {
1967
+ this.emit(`collection:${data.collection}:${data.id}`, action, payload);
1951
1968
  }
1952
1969
  }
1953
- joinTopic(topic, joinPayload) {
1954
- const ref = this.nextRef();
1955
- const msg = JSON.stringify({
1956
- topic,
1957
- event: "phx_join",
1958
- payload: joinPayload ?? {},
1959
- ref
1960
- });
1961
- this.ws?.send(msg);
1962
- }
1963
- nextRef() {
1964
- this.refCounter++;
1965
- return this.refCounter.toString();
1966
- }
1967
- startHeartbeat() {
1968
- this.stopHeartbeat();
1969
- this.heartbeatInterval = setInterval(() => {
1970
- if (this.ws?.readyState === WebSocket.OPEN) {
1971
- const ref = this.nextRef();
1972
- const msg = JSON.stringify({
1973
- topic: "phoenix",
1974
- event: "heartbeat",
1975
- payload: {},
1976
- ref
1977
- });
1978
- this.ws.send(msg);
1970
+ emit(topic, event, payload) {
1971
+ const subs = this.subscriptions.get(topic);
1972
+ if (!subs) return;
1973
+ const e = { event, topic, payload };
1974
+ for (const s of subs) {
1975
+ try {
1976
+ s.callback(e);
1977
+ } catch {
1979
1978
  }
1980
- }, 3e4);
1981
- }
1982
- stopHeartbeat() {
1983
- if (this.heartbeatInterval) {
1984
- clearInterval(this.heartbeatInterval);
1985
- this.heartbeatInterval = null;
1986
1979
  }
1987
1980
  }
1988
- // ── Reconnect ──
1981
+ closeStream() {
1982
+ const controller = this.controller;
1983
+ this.controller = null;
1984
+ this.open = false;
1985
+ controller?.abort();
1986
+ }
1989
1987
  scheduleReconnect() {
1988
+ if (this.closed) return;
1990
1989
  this.clearReconnectTimer();
1991
1990
  const delay = Math.min(
1992
1991
  1e3 * 2 ** this.reconnectAttempt,
@@ -1995,7 +1994,6 @@ var RealtimeService = class {
1995
1994
  this.reconnectAttempt++;
1996
1995
  this.reconnectTimer = setTimeout(() => {
1997
1996
  this.reconnectTimer = null;
1998
- this.onReconnect?.();
1999
1997
  this.doConnect();
2000
1998
  }, delay);
2001
1999
  }
@@ -2008,14 +2006,18 @@ var RealtimeService = class {
2008
2006
  };
2009
2007
 
2010
2008
  // src/files.ts
2011
- function getFileUrl(baseUrl, fileId) {
2012
- return baseUrl.replace(/\/+$/, "") + "/files/" + encodeURIComponent(fileId);
2009
+ function encodeKey(key) {
2010
+ return key.split("/").map(encodeURIComponent).join("/");
2011
+ }
2012
+ function getFileUrl(baseUrl, key) {
2013
+ return baseUrl.replace(/\/+$/, "") + "/files/" + encodeKey(key);
2013
2014
  }
2014
- function getThumbUrl(baseUrl, fileId, size) {
2015
- return baseUrl.replace(/\/+$/, "") + "/files/" + encodeURIComponent(fileId) + "/thumbs/" + encodeURIComponent(size);
2015
+ function getThumbUrl(baseUrl, key, size) {
2016
+ return getFileUrl(baseUrl, key) + "?thumb=" + encodeURIComponent(size);
2016
2017
  }
2017
- function getScaleUrl(baseUrl, fileId, size) {
2018
- return baseUrl.replace(/\/+$/, "") + "/files/" + encodeURIComponent(fileId) + "/scale/" + encodeURIComponent(size);
2018
+ function getScaleUrl(baseUrl, key, size) {
2019
+ const parameter = size.includes("x") ? "thumb" : "preset";
2020
+ return getFileUrl(baseUrl, key) + "?" + parameter + "=" + encodeURIComponent(size);
2019
2021
  }
2020
2022
  function getVariantUrl(baseUrl, fileId, preset) {
2021
2023
  return getScaleUrl(baseUrl, fileId, preset);
@@ -2686,7 +2688,7 @@ var LazypockClient = class {
2686
2688
  this.http = new HttpClient(baseUrl, this.authStore, connectionId);
2687
2689
  this.realtime = options.realtime ?? new RealtimeService();
2688
2690
  if (!options.realtime) {
2689
- this.realtime.setUrl(wsUrlFromBaseUrl(baseUrl));
2691
+ this.realtime.setUrl(sseUrlFromBaseUrl(baseUrl));
2690
2692
  }
2691
2693
  this.realtime.setConnectionId(connectionId);
2692
2694
  this.realtime.setTokenProvider(() => this.authStore.token);
@@ -2817,7 +2819,7 @@ var LazypockClient = class {
2817
2819
  async login(email, password, collection) {
2818
2820
  let data;
2819
2821
  if (collection) {
2820
- data = await this.http.post("/" + encodeURIComponent(collection) + "/auth-with-password", {
2822
+ data = await this.http.post("/collections/" + encodeURIComponent(collection) + "/auth-with-password", {
2821
2823
  identity: email,
2822
2824
  password
2823
2825
  });
@@ -2827,7 +2829,7 @@ var LazypockClient = class {
2827
2829
  }
2828
2830
  } else {
2829
2831
  try {
2830
- data = await this.http.post("/_superusers/auth-with-password", {
2832
+ data = await this.http.post("/collections/_superusers/auth-with-password", {
2831
2833
  identity: email,
2832
2834
  password
2833
2835
  });
@@ -2867,7 +2869,7 @@ var LazypockClient = class {
2867
2869
  */
2868
2870
  async authWithPassword(collection, identity, password, options) {
2869
2871
  const data = await this.http.post(
2870
- "/" + encodeURIComponent(collection) + "/auth-with-password",
2872
+ "/collections/" + encodeURIComponent(collection) + "/auth-with-password",
2871
2873
  { identity, password },
2872
2874
  options
2873
2875
  );
@@ -2886,7 +2888,7 @@ var LazypockClient = class {
2886
2888
  */
2887
2889
  async authRefresh(collection, options) {
2888
2890
  const data = await this.http.post(
2889
- "/" + encodeURIComponent(collection) + "/auth-refresh",
2891
+ "/collections/" + encodeURIComponent(collection) + "/auth-refresh",
2890
2892
  void 0,
2891
2893
  options
2892
2894
  );
@@ -2939,6 +2941,6 @@ function createClient(options) {
2939
2941
  getThumbUrl,
2940
2942
  getVariantUrl,
2941
2943
  schemaFieldType,
2942
- wsUrlFromBaseUrl
2944
+ sseUrlFromBaseUrl
2943
2945
  });
2944
2946
  //# sourceMappingURL=index.cjs.map