@symbo.ls/fetch 3.14.661 → 3.14.662
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/CHANGELOG.md +36 -0
- package/README.md +221 -35
- package/adapters/rest.js +165 -26
- package/dist/cjs/adapters/rest.js +1 -1
- package/dist/cjs/early.js +1 -0
- package/dist/cjs/earlyScript.js +53 -0
- package/dist/cjs/index.js +1 -1
- package/dist/esm/adapters/rest.js +1 -1
- package/dist/esm/early.js +1 -0
- package/dist/esm/earlyScript.js +53 -0
- package/dist/esm/index.js +1 -1
- package/early.js +160 -0
- package/earlyScript.js +204 -0
- package/index.js +490 -119
- package/package.json +9 -2
package/adapters/rest.js
CHANGED
|
@@ -1,6 +1,12 @@
|
|
|
1
1
|
'use strict'
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
import { openEarly, takeEarly, earlyKey, isScalarParams, withReads } from '../early.js'
|
|
4
|
+
|
|
5
|
+
// `buildUrl` and `selectQuery` are the address of a GET. The pre-boot script
|
|
6
|
+
// of `fetch.early` (earlyScript.js) embeds both BY SOURCE, so an early request
|
|
7
|
+
// and the adapter's own are built by the same code — keep them
|
|
8
|
+
// self-contained: nothing but their parameters and the platform's built-ins.
|
|
9
|
+
export const buildUrl = (base, from, params) => {
|
|
4
10
|
const slash = from && !from.startsWith('/') ? '/' : ''
|
|
5
11
|
const url = new URL(`${base}${slash}${from}`)
|
|
6
12
|
if (params) {
|
|
@@ -14,6 +20,26 @@ const buildUrl = (base, from, params) => {
|
|
|
14
20
|
return url.toString()
|
|
15
21
|
}
|
|
16
22
|
|
|
23
|
+
// The query string of a `select`: its params, then select / limit / offset /
|
|
24
|
+
// single / order.
|
|
25
|
+
export const selectQuery = ({ params, select, limit, offset, order, single }) => {
|
|
26
|
+
const allParams = { ...params }
|
|
27
|
+
if (select) allParams.select = select
|
|
28
|
+
if (limit) allParams.limit = limit
|
|
29
|
+
if (offset) allParams.offset = offset
|
|
30
|
+
if (single) allParams.single = true
|
|
31
|
+
if (order) {
|
|
32
|
+
if (typeof order === 'string') {
|
|
33
|
+
allParams.order = order
|
|
34
|
+
} else if (Array.isArray(order)) {
|
|
35
|
+
allParams.order = order.map(o => `${o.by}:${o.asc === false ? 'desc' : 'asc'}`).join(',')
|
|
36
|
+
} else if (order.by) {
|
|
37
|
+
allParams.order = `${order.by}:${order.asc === false ? 'desc' : 'asc'}`
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
return allParams
|
|
41
|
+
}
|
|
42
|
+
|
|
17
43
|
const typeTag = (value) => Object.prototype.toString.call(value).slice(8, -1)
|
|
18
44
|
|
|
19
45
|
// --- Responses ---
|
|
@@ -65,13 +91,16 @@ const readErrorBody = async (res) => {
|
|
|
65
91
|
// read as a success.
|
|
66
92
|
const errorMessage = (body, res) => body?.message || body?.error || res.statusText || `HTTP ${res.status}`
|
|
67
93
|
|
|
68
|
-
const request = async (url, options, responseType) => {
|
|
94
|
+
const request = async (url, options, responseType, early) => {
|
|
69
95
|
const type = responseType == null ? 'auto' : responseType
|
|
70
96
|
if (!RESPONSE_TYPES.includes(type)) {
|
|
71
97
|
throw new TypeError(`@symbo.ls/fetch rest: unknown responseType "${type}" — use one of: ${RESPONSE_TYPES.join(', ')}`)
|
|
72
98
|
}
|
|
73
99
|
|
|
74
|
-
|
|
100
|
+
// `early` — the pre-boot script's answer to this very request (fetch.early),
|
|
101
|
+
// read exactly like the adapter's own; when that GET failed or was refused,
|
|
102
|
+
// the request is sent as usual.
|
|
103
|
+
const res = (early && await early) || await globalThis.fetch(url, options)
|
|
75
104
|
|
|
76
105
|
if (type === 'auto') {
|
|
77
106
|
const data = await readAuto(res)
|
|
@@ -142,14 +171,108 @@ const mergeHeaders = (...sources) => {
|
|
|
142
171
|
const JSON_TYPE = { 'Content-Type': 'application/json' }
|
|
143
172
|
const NO_TYPE = { 'Content-Type': undefined }
|
|
144
173
|
|
|
145
|
-
|
|
174
|
+
// --- Anonymous reads (`reads`) ---
|
|
175
|
+
//
|
|
176
|
+
// Every RPC was a POST with a JSON body and every call carried the configured
|
|
177
|
+
// `apikey` header: neither is a "simple" request, so a cross-origin backend
|
|
178
|
+
// (Supabase, PostgREST behind a gateway) answered each read only after a CORS
|
|
179
|
+
// preflight — one extra round trip per read (xma.info report #18). `reads`
|
|
180
|
+
// (opt-in) sends an ANONYMOUS read as a simple GET instead:
|
|
181
|
+
// - `query: { apikey: 'apikey' }` — configured header → query parameter.
|
|
182
|
+
// The header leaves the request and travels in the URL. Only for a PUBLIC
|
|
183
|
+
// key the backend reads from the query string (Supabase's gateway reads
|
|
184
|
+
// `apikey`): a URL lands in logs and history.
|
|
185
|
+
// - `rpc: 'get'` — the backend answers read-only RPCs as GETs with the
|
|
186
|
+
// arguments in the query string (PostgREST: STABLE/IMMUTABLE functions).
|
|
187
|
+
// Only a call marked `read: true` (the plugin marks a declarative rpc
|
|
188
|
+
// query; never an action) with scalar arguments (isScalarParams) goes so.
|
|
189
|
+
// The same two names as `fetch.early`, which defaults to them (withReads):
|
|
190
|
+
// one declaration drives the pre-boot script and the adapter, so the GET the
|
|
191
|
+
// script sent is the GET the call would send, and it is adopted.
|
|
192
|
+
//
|
|
193
|
+
// A call that carries an Authorization header (the adapter's token, a
|
|
194
|
+
// per-call one) is NOT anonymous: it keeps the header path unchanged — a
|
|
195
|
+
// session token never moves into a URL, and its request stays a POST/headers
|
|
196
|
+
// request exactly as before. No `reads` → nothing changes.
|
|
197
|
+
const openReads = (config) => {
|
|
198
|
+
if (!config || typeof config !== 'object') return null
|
|
199
|
+
const params = {}
|
|
200
|
+
for (const name in config.query || {}) params[name.toLowerCase()] = config.query[name]
|
|
201
|
+
return { params, rpc: config.rpc === 'get' }
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
// A GET has no body, so a configured Content-Type describes nothing — and it
|
|
205
|
+
// is no CORS-safelisted header for application/json: dropped from a read GET.
|
|
206
|
+
const CONTENT_TYPE = 'content-type'
|
|
207
|
+
|
|
208
|
+
const withQuery = (url, query) => {
|
|
209
|
+
const names = Object.keys(query)
|
|
210
|
+
if (!names.length) return url
|
|
211
|
+
const parsed = new URL(url)
|
|
212
|
+
for (const name of names) parsed.searchParams.set(name, query[name])
|
|
213
|
+
return parsed.toString()
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
export const setup = async ({ url, headers, auth, fetchOptions, early, reads }) => {
|
|
146
217
|
if (!url) throw new Error('@symbo.ls/fetch rest: url is required')
|
|
147
|
-
return restAdapter(url, headers, auth, fetchOptions)
|
|
218
|
+
return restAdapter(url, headers, auth, fetchOptions, early, reads)
|
|
148
219
|
}
|
|
149
220
|
|
|
150
|
-
export const restAdapter = (baseUrl, defaultHeaders = {}, authConfig, defaultFetchOptions = {}) => {
|
|
221
|
+
export const restAdapter = (baseUrl, defaultHeaders = {}, authConfig, defaultFetchOptions = {}, earlyConfig, readsConfig) => {
|
|
151
222
|
let token = authConfig?.token || null
|
|
152
223
|
|
|
224
|
+
// `fetch.early` (early.js): what the pre-boot script may have asked for
|
|
225
|
+
// already. null without the opt-in — then no call ever looks. Its `query`
|
|
226
|
+
// and `rpc` default to `reads` — the same defaults the script is built with.
|
|
227
|
+
const early = openEarly(withReads(earlyConfig, readsConfig), defaultHeaders)
|
|
228
|
+
const reads = openReads(readsConfig)
|
|
229
|
+
|
|
230
|
+
// An anonymous read's request: the headers it sends (the `reads.query` ones
|
|
231
|
+
// and Content-Type removed) and the query parameters the moved ones became.
|
|
232
|
+
// `adoptHeaders` is what an early answer is matched against — the sent
|
|
233
|
+
// headers plus the moved ones at their value, so an answer the script got
|
|
234
|
+
// with another key is never taken. null without `reads`, or for a call
|
|
235
|
+
// with an Authorization header (not anonymous: the header path stays).
|
|
236
|
+
const anonymousRead = (merged) => {
|
|
237
|
+
if (!reads) return null
|
|
238
|
+
const headers = {}
|
|
239
|
+
const adoptHeaders = {}
|
|
240
|
+
const query = {}
|
|
241
|
+
for (const name in merged) {
|
|
242
|
+
const lower = name.toLowerCase()
|
|
243
|
+
if (lower === 'authorization') return null
|
|
244
|
+
if (lower === CONTENT_TYPE) continue
|
|
245
|
+
adoptHeaders[name] = merged[name]
|
|
246
|
+
const param = reads.params[lower]
|
|
247
|
+
if (param) query[param] = merged[name]
|
|
248
|
+
else headers[name] = merged[name]
|
|
249
|
+
}
|
|
250
|
+
return { headers, adoptHeaders, query }
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
// The early answer to this call, if one waits for exactly it: the same URL
|
|
254
|
+
// and Accept-Language, and no header the early GET did not carry. The
|
|
255
|
+
// configured headers it carried as query parameters (early.query) count
|
|
256
|
+
// only at their configured value; anything else — the adapter's token, a
|
|
257
|
+
// per-call Authorization, any other header — means the call is not the
|
|
258
|
+
// anonymous GET the script sent, so it never takes that answer. `address`
|
|
259
|
+
// builds the GET's URL; one the URL parser refuses (a relative base) was
|
|
260
|
+
// never sent early, and looking must never break the call itself.
|
|
261
|
+
const adopt = (address, headers) => {
|
|
262
|
+
if (!early) return null
|
|
263
|
+
let lang = ''
|
|
264
|
+
for (const name in headers) {
|
|
265
|
+
const lower = name.toLowerCase()
|
|
266
|
+
if (lower === 'accept-language') lang = String(headers[name])
|
|
267
|
+
else if (early.carried[lower] !== headers[name]) return null
|
|
268
|
+
}
|
|
269
|
+
try {
|
|
270
|
+
return takeEarly(earlyKey(address(), lang), early.maxAge)
|
|
271
|
+
} catch (e) {
|
|
272
|
+
return null
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
|
|
153
276
|
// Precedence, lowest first: the configured headers, the adapter's token, the
|
|
154
277
|
// body's Content-Type, then the call's own `headers` — so one call can send
|
|
155
278
|
// its own Bearer token (a per-user token) or its own Content-Type.
|
|
@@ -223,30 +346,46 @@ export const restAdapter = (baseUrl, defaultHeaders = {}, authConfig, defaultFet
|
|
|
223
346
|
|
|
224
347
|
// CRUD — every call takes `headers` (merged over the configured ones),
|
|
225
348
|
// `baseUrl` and `responseType`.
|
|
349
|
+
// A select is a GET. With `reads.query` an anonymous one carries the
|
|
350
|
+
// configured key in its query string instead of a header (no preflight).
|
|
226
351
|
select: ({ from, params, select, limit, offset, order, single, headers, baseUrl: fromBase, responseType }) => {
|
|
227
|
-
const
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
if (
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
if (typeof order === 'string') {
|
|
234
|
-
allParams.order = order
|
|
235
|
-
} else if (Array.isArray(order)) {
|
|
236
|
-
allParams.order = order.map(o => `${o.by}:${o.asc === false ? 'desc' : 'asc'}`).join(',')
|
|
237
|
-
} else if (order.by) {
|
|
238
|
-
allParams.order = `${order.by}:${order.asc === false ? 'desc' : 'asc'}`
|
|
239
|
-
}
|
|
352
|
+
const url = buildUrl(fromBase || baseUrl, from || '', selectQuery({ params, select, limit, offset, order, single }))
|
|
353
|
+
const merged = getHeaders(headers)
|
|
354
|
+
const anonymous = anonymousRead(merged)
|
|
355
|
+
if (anonymous) {
|
|
356
|
+
const options = getFetchOptions({ headers: anonymous.headers })
|
|
357
|
+
return request(withQuery(url, anonymous.query), options, responseType, adopt(() => url, anonymous.adoptHeaders))
|
|
240
358
|
}
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
getFetchOptions({ headers: getHeaders(headers) }),
|
|
244
|
-
responseType
|
|
245
|
-
)
|
|
359
|
+
const options = getFetchOptions({ headers: merged })
|
|
360
|
+
return request(url, options, responseType, adopt(() => url, options.headers))
|
|
246
361
|
},
|
|
247
362
|
|
|
248
|
-
|
|
249
|
-
|
|
363
|
+
// An RPC is a POST. With `reads.rpc: 'get'` an anonymous call marked
|
|
364
|
+
// `read: true` whose arguments read back the same from a query string
|
|
365
|
+
// is a GET with them in the query instead. With `early.rpc: 'get'` the
|
|
366
|
+
// pre-boot script sent the read ones as GETs; this call takes such an
|
|
367
|
+
// answer when its own arguments read back the same from there.
|
|
368
|
+
rpc: async ({ from, params, headers, baseUrl: fromBase, responseType, read }) => {
|
|
369
|
+
const scalar = isScalarParams(params)
|
|
370
|
+
const address = () => buildUrl(fromBase || baseUrl, `rpc/${from}`, params)
|
|
371
|
+
const post = (taken) => request(resolveUrl(`rpc/${from}`, fromBase), withBody('POST', params, headers), responseType, taken)
|
|
372
|
+
const merged = getHeaders(headers)
|
|
373
|
+
const anonymous = read === true && reads && reads.rpc && scalar ? anonymousRead(merged) : null
|
|
374
|
+
// An address the URL parser refuses (a relative base) cannot carry a
|
|
375
|
+
// query: such a call stays a POST.
|
|
376
|
+
let url = null
|
|
377
|
+
if (anonymous) {
|
|
378
|
+
try { url = address() } catch (e) { url = null }
|
|
379
|
+
}
|
|
380
|
+
if (!url) return post(early && early.rpc && scalar ? adopt(address, merged) : null)
|
|
381
|
+
|
|
382
|
+
const options = getFetchOptions({ method: 'GET', headers: anonymous.headers })
|
|
383
|
+
const result = await request(withQuery(url, anonymous.query), options, responseType, adopt(() => url, anonymous.adoptHeaders))
|
|
384
|
+
// 405: the backend serves this function only as a POST (PostgREST runs
|
|
385
|
+
// a GET read-only and refuses a VOLATILE function that writes with 405
|
|
386
|
+
// before anything was written) — the call's own POST decides.
|
|
387
|
+
return result.status === 405 ? post(null) : result
|
|
388
|
+
},
|
|
250
389
|
|
|
251
390
|
insert: ({ from, data, headers, baseUrl: fromBase, responseType }) =>
|
|
252
391
|
request(resolveUrl(from, fromBase), withBody('POST', data, headers), responseType),
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var B=Object.defineProperty;var D=Object.getOwnPropertyDescriptor;var F=Object.getOwnPropertyNames;var G=Object.prototype.hasOwnProperty;var z=(t,e)=>{for(var s in e)B(t,s,{get:e[s],enumerable:!0})},M=(t,e,s,d)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of F(e))!G.call(t,r)&&r!==s&&B(t,r,{get:()=>e[r],enumerable:!(d=D(e,r))||d.enumerable});return t};var Q=t=>M(B({},"__esModule",{value:!0}),t);var ot={};z(ot,{buildUrl:()=>L,restAdapter:()=>Y,selectQuery:()=>W,setup:()=>rt});module.exports=Q(ot);var w=require("../early.js");const L=(t,e,s)=>{const d=e&&!e.startsWith("/")?"/":"",r=new URL(`${t}${d}${e}`);if(s)for(const c in s){const o=s[c];o!=null&&r.searchParams.set(c,typeof o=="object"?JSON.stringify(o):o)}return r.toString()},W=({params:t,select:e,limit:s,offset:d,order:r,single:c})=>{const o={...t};return e&&(o.select=e),s&&(o.limit=s),d&&(o.offset=d),c&&(o.single=!0),r&&(typeof r=="string"?o.order=r:Array.isArray(r)?o.order=r.map(T=>`${T.by}:${T.asc===!1?"desc":"asc"}`).join(","):r.by&&(o.order=`${r.by}:${r.asc===!1?"desc":"asc"}`)),o},_=t=>Object.prototype.toString.call(t).slice(8,-1),q=["auto","json","text","blob","arrayBuffer","stream","response"],K={json:async t=>{const e=await t.text();return e?JSON.parse(e):null},text:t=>t.text(),blob:t=>t.blob(),arrayBuffer:t=>t.arrayBuffer(),stream:t=>t.body,response:t=>t},V=t=>{const e=t.headers.get("content-type");return e&&e.includes("json")?t.json():t.text()},v=async t=>{const e=await t.text(),s=t.headers.get("content-type");if(e&&s&&s.includes("json"))try{return JSON.parse(e)}catch{}return e},J=(t,e)=>t?.message||t?.error||e.statusText||`HTTP ${e.status}`,f=async(t,e,s,d)=>{const r=s??"auto";if(!q.includes(r))throw new TypeError(`@symbo.ls/fetch rest: unknown responseType "${r}" \u2014 use one of: ${q.join(", ")}`);const c=d&&await d||await globalThis.fetch(t,e);if(r==="auto"){const o=await V(c);return{data:o,error:c.ok?null:J(o,c),status:c.status}}if(!c.ok){const o=await v(r==="response"?c.clone():c);return{data:r==="response"?c:o,error:J(o,c),status:c.status}}return{data:await K[r](c),error:null,status:c.status}},X=["FormData","Blob","File","URLSearchParams","ReadableStream","ArrayBuffer"],Z=t=>t!==null&&typeof t=="object"&&(ArrayBuffer.isView(t)||X.includes(_(t))),C=t=>Array.isArray(t)?t:typeof t.entries=="function"?t.entries():Object.entries(t),N=(...t)=>{const e={},s=new Map;for(const d of t)if(d)for(const[r,c]of C(d)){const o=r.toLowerCase();if(s.has(o)&&delete e[s.get(o)],c==null){s.delete(o);continue}s.set(o,r),e[r]=c}return e},tt={"Content-Type":"application/json"},et={"Content-Type":void 0},nt=t=>{if(!t||typeof t!="object")return null;const e={};for(const s in t.query||{})e[s.toLowerCase()]=t.query[s];return{params:e,rpc:t.rpc==="get"}},st="content-type",I=(t,e)=>{const s=Object.keys(e);if(!s.length)return t;const d=new URL(t);for(const r of s)d.searchParams.set(r,e[r]);return d.toString()},rt=async({url:t,headers:e,auth:s,fetchOptions:d,early:r,reads:c})=>{if(!t)throw new Error("@symbo.ls/fetch rest: url is required");return Y(t,e,s,d,r,c)},Y=(t,e={},s,d={},r,c)=>{let o=s?.token||null;const T=(0,w.openEarly)((0,w.withReads)(r,c),e),x=nt(c),H=n=>{if(!x)return null;const a={},l={},i={};for(const u in n){const p=u.toLowerCase();if(p==="authorization")return null;if(p===st)continue;l[u]=n[u];const y=x.params[p];y?i[y]=n[u]:a[u]=n[u]}return{headers:a,adoptHeaders:l,query:i}},A=(n,a)=>{if(!T)return null;let l="";for(const i in a){const u=i.toLowerCase();if(u==="accept-language")l=String(a[i]);else if(T.carried[u]!==a[i])return null}try{return(0,w.takeEarly)((0,w.earlyKey)(n(),l),T.maxAge)}catch{return null}},R=()=>o?{Authorization:`Bearer ${o}`}:null,E=n=>N(e,R(),n),S=n=>({...d,...n}),P=(n,a,l)=>{if(!Z(a))return S({method:n,headers:N(e,R(),tt,l),body:JSON.stringify(a)});const i={method:n,headers:N(e,R(),et,l),body:a};return _(a)==="ReadableStream"&&(i.duplex="half"),S(i)},$=(n,a)=>{const l=a||t;if(n&&(n.startsWith("http://")||n.startsWith("https://")))return n;const i=n&&!n.startsWith("/")?"/":"";return`${l}${i}${n||""}`};return{name:"rest",setToken:n=>{o=n},getSession:async()=>{if(!s?.sessionUrl)return o?{token:o}:null;const n=await f($(s.sessionUrl,s.baseUrl),S({headers:E()}));return n.error?null:n.data},signIn:async n=>{if(!s?.signInUrl)throw new Error("rest: auth.signInUrl not configured");const a=await f($(s.signInUrl,s.baseUrl),P("POST",n));return a.data?.token&&(o=a.data.token),a},signOut:async()=>(s?.signOutUrl&&await f($(s.signOutUrl,s.baseUrl),S({method:"POST",headers:E()})),o=null,{error:null}),select:({from:n,params:a,select:l,limit:i,offset:u,order:p,single:y,headers:h,baseUrl:O,responseType:m})=>{const b=L(O||t,n||"",W({params:a,select:l,limit:i,offset:u,order:p,single:y})),U=E(h),g=H(U);if(g){const k=S({headers:g.headers});return f(I(b,g.query),k,m,A(()=>b,g.adoptHeaders))}const j=S({headers:U});return f(b,j,m,A(()=>b,j.headers))},rpc:async({from:n,params:a,headers:l,baseUrl:i,responseType:u,read:p})=>{const y=(0,w.isScalarParams)(a),h=()=>L(i||t,`rpc/${n}`,a),O=k=>f($(`rpc/${n}`,i),P("POST",a,l),u,k),m=E(l),b=p===!0&&x&&x.rpc&&y?H(m):null;let U=null;if(b)try{U=h()}catch{U=null}if(!U)return O(T&&T.rpc&&y?A(h,m):null);const g=S({method:"GET",headers:b.headers}),j=await f(I(U,b.query),g,u,A(()=>U,b.adoptHeaders));return j.status===405?O(null):j},insert:({from:n,data:a,headers:l,baseUrl:i,responseType:u})=>f($(n,i),P("POST",a,l),u),update:({from:n,data:a,params:l,method:i,headers:u,baseUrl:p,responseType:y})=>{const h=l?.id||a?.id,O=h?`${n}/${h}`:n;return f($(O,p),P(i||"PATCH",a,u),y)},upsert:({from:n,data:a,params:l,method:i,headers:u,baseUrl:p,responseType:y})=>{const h=l?.id||a?.id,O=h?`${n}/${h}`:n;return f($(O,p),P(i||"PUT",a,u),y)},delete:({from:n,params:a,headers:l,baseUrl:i,responseType:u})=>{const p=a?.id,y=p?`${n}/${p}`:n;return f($(y,i),S({method:"DELETE",headers:E(l)}),u)}}};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";var y=Object.defineProperty;var g=Object.getOwnPropertyDescriptor;var h=Object.getOwnPropertyNames;var A=Object.prototype.hasOwnProperty;var x=(e,t)=>{for(var r in t)y(e,r,{get:t[r],enumerable:!0})},m=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of h(t))!A.call(e,o)&&o!==r&&y(e,o,{get:()=>t[o],enumerable:!(n=g(t,o))||n.enumerable});return e};var E=e=>m(y({},"__esModule",{value:!0}),e);var C={};x(C,{EARLY_KEY:()=>b,EARLY_MAX_AGE:()=>w,dropEarly:()=>q,earlyKey:()=>L,isScalarParams:()=>R,matchEarlyRoute:()=>_,openEarly:()=>Y,takeEarly:()=>k,withReads:()=>j});module.exports=E(C);const b="@symbo.ls/fetch:EARLY",w=3e4,L=(e,t)=>{const r=new URL(e);return r.searchParams.sort(),r.toString()+" "+(t||"")},R=e=>{if(e==null)return!0;if(typeof e!="object"||Array.isArray(e))return!1;const t=Object.getPrototypeOf(e);if(t!==Object.prototype&&t!==null)return!1;for(const r in e){const n=e[r];if(!(n===void 0||typeof n=="string"||typeof n=="boolean")&&!(typeof n=="number"&&isFinite(n)))return!1}return!0},_=(e,t)=>{const r=i=>String(i).split("/").filter(Boolean),n=r(t);let o=null;for(let i=0;i<e.length;i++){const s=r(e[i]),l=s[s.length-1]==="*",f=l?s.length-1:s.length;if(l?n.length<f:n.length!==f)continue;const d={};let u=l?-1:0,a=!0;for(let c=0;c<f;c++)if(s[c].charAt(0)===":"){try{d[s[c].slice(1)]=decodeURIComponent(n[c])}catch{a=!1;break}u+=1}else if(s[c]===n[c])u+=3;else{a=!1;break}a&&(!o||u>o.score)&&(o={index:i,params:d,score:u})}return o&&{index:o.index,params:o.params}},p=()=>Symbol.for(b),j=(e,t)=>{if(!e||typeof e!="object"||!t||typeof t!="object")return e;const r={...e};return r.query===void 0&&t.query!==void 0&&(r.query=t.query),r.rpc===void 0&&t.rpc!==void 0&&(r.rpc=t.rpc),r},Y=(e,t)=>{if(!e||typeof e!="object")return null;const r=p();let n=globalThis[r];n||(n={time:Date.now(),entries:{}},globalThis[r]=n),n.closed=!0;const o={};for(const s in e.query||{})for(const l in t||{})l.toLowerCase()===s.toLowerCase()&&(o[l.toLowerCase()]=t[l]);const i=typeof e.maxAge=="number"&&e.maxAge>=0?e.maxAge:3e4;return{carried:o,rpc:e.rpc==="get",maxAge:i}},k=(e,t=3e4)=>{const r=globalThis[p()],n=r&&r.entries&&r.entries[e];return!n||(delete r.entries[e],!(Date.now()-n.time<=t))?null:Promise.resolve(n.answer).then(o=>o&&o.ok&&!o.bodyUsed?o:null,()=>null)},q=()=>{const e=globalThis[p()];e&&e.entries&&(e.entries={})};
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
"use strict";var u=Object.defineProperty;var h=Object.getOwnPropertyDescriptor;var m=Object.getOwnPropertyNames;var p=Object.prototype.hasOwnProperty;var d=(e,r)=>{for(var t in r)u(e,t,{get:r[t],enumerable:!0})},v=(e,r,t,s)=>{if(r&&typeof r=="object"||typeof r=="function")for(let a of m(r))!p.call(e,a)&&a!==t&&u(e,a,{get:()=>r[a],enumerable:!(s=h(r,a))||s.enumerable});return e};var b=e=>v(u({},"__esModule",{value:!0}),e);var L={};d(L,{createEarlyScript:()=>g,default:()=>E});module.exports=b(L);var n=require("./adapters/rest.js"),o=require("./early.js");const q="smbls_lang",S=["credentials","mode","cache","redirect","referrerPolicy","priority"],l=e=>{try{return new Function(e),!0}catch{return!1}},w=(e,r)=>{const t=typeof e=="function"?e.toString():String(e).trim();if(l("return ("+t+")"))return"("+t+")";if(l("return ({"+t+"})"))return"Object.values({"+t+"})[0]";throw new Error(`@symbo.ls/fetch early: the request function of ${r} does not compile on its own`)},f=(e,r)=>typeof e=="function"||typeof e=="string"?w(e,r):JSON.stringify(Array.isArray(e)?e:[]),O=e=>{const r=e.state&&typeof e.state.lang=="string"?e.state.lang:"",t=e.polyglot;return t&&typeof t=="object"?{storage:t.storageLangKey||q,fallback:r||t.defaultLang||"en"}:{storage:"",fallback:r}},k=(e,r)=>{const t={};for(const s in e||{}){const a=Object.keys(r||{}).find(c=>c.toLowerCase()===s.toLowerCase());if(!a)throw new Error(`@symbo.ls/fetch early.query: "${s}" is not one of the adapter's configured headers`);t[e[s]]=r[a]}return t},$=e=>{const r={};for(const t of S)e&&e[t]!==void 0&&(r[t]=e[t]);return r.cache===void 0&&(r.cache="no-store"),r},g=(e={})=>{const r=e&&e.fetch,t=r&&(0,o.withReads)(r.early,r.reads);if(!t||typeof t!="object"||r.adapter!=="rest"||!r.url)return"";const s=t.routes&&typeof t.routes=="object"?Object.keys(t.routes):[];if(!s.length&&!t.always)return"";const a={url:r.url,query:k(t.query,r.headers),rpc:t.rpc==="get",fetchOptions:$(r.fetchOptions),lang:O(e)},c=s.map(i=>`[${JSON.stringify(i)}, ${f(t.routes[i],JSON.stringify(i))}]`).join(`,
|
|
2
|
+
`),y=t.always?f(t.always,"`always`"):"[]";return`/* @symbo.ls/fetch \u2014 fetch.early: the first view's requests, sent before the app boots */
|
|
3
|
+
;(function () {
|
|
4
|
+
var g = globalThis
|
|
5
|
+
var K = Symbol.for(${JSON.stringify(o.EARLY_KEY)})
|
|
6
|
+
if (g[K] || typeof g.fetch !== 'function' || !g.location) return
|
|
7
|
+
var registry = g[K] = { time: Date.now(), entries: {} }
|
|
8
|
+
var config = ${JSON.stringify(a)}
|
|
9
|
+
var buildUrl = ${n.buildUrl.toString()}
|
|
10
|
+
var selectQuery = ${n.selectQuery.toString()}
|
|
11
|
+
var earlyKey = ${o.earlyKey.toString()}
|
|
12
|
+
var isScalarParams = ${o.isScalarParams.toString()}
|
|
13
|
+
var matchEarlyRoute = ${o.matchEarlyRoute.toString()}
|
|
14
|
+
var always = ${y}
|
|
15
|
+
var routes = [
|
|
16
|
+
${c}
|
|
17
|
+
]
|
|
18
|
+
var storage = function (key) {
|
|
19
|
+
try { return key ? g.localStorage.getItem(key) : null } catch (e) { return null }
|
|
20
|
+
}
|
|
21
|
+
var lang = (config.lang.storage && storage(config.lang.storage)) || config.lang.fallback || ''
|
|
22
|
+
var ctx = { path: g.location.pathname, query: new URLSearchParams(g.location.search), lang: lang, storage: storage }
|
|
23
|
+
var list = function (requests, params) {
|
|
24
|
+
try {
|
|
25
|
+
var out = typeof requests === 'function' ? requests(params, ctx) : requests
|
|
26
|
+
return Array.isArray(out) ? out : []
|
|
27
|
+
} catch (e) {
|
|
28
|
+
return []
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
var match = matchEarlyRoute(routes.map(function (route) { return route[0] }), ctx.path)
|
|
32
|
+
var requests = list(always, {}).concat(match ? list(routes[match.index][1], match.params) : [])
|
|
33
|
+
for (var i = 0; i < requests.length; i++) {
|
|
34
|
+
try {
|
|
35
|
+
var request = requests[i]
|
|
36
|
+
if (!request || typeof request !== 'object' || !request.from) continue
|
|
37
|
+
var method = request.method || 'select'
|
|
38
|
+
var url
|
|
39
|
+
if (method === 'select') url = buildUrl(config.url, request.from, selectQuery(request))
|
|
40
|
+
else if (method === 'rpc' && config.rpc && isScalarParams(request.params)) url = buildUrl(config.url, 'rpc/' + request.from, request.params)
|
|
41
|
+
else continue
|
|
42
|
+
var language = request.lang === false ? '' : lang
|
|
43
|
+
var key = earlyKey(url, language)
|
|
44
|
+
if (registry.entries[key]) continue
|
|
45
|
+
var address = new URL(url)
|
|
46
|
+
for (var name in config.query) address.searchParams.set(name, config.query[name])
|
|
47
|
+
var options = Object.assign({}, config.fetchOptions, { method: 'GET' })
|
|
48
|
+
if (language) options.headers = { 'Accept-Language': language }
|
|
49
|
+
registry.entries[key] = { time: Date.now(), answer: g.fetch(address.toString(), options).catch(function () { return null }) }
|
|
50
|
+
} catch (e) {}
|
|
51
|
+
}
|
|
52
|
+
})()
|
|
53
|
+
`.replace(/<\/script/gi,"<\\/script")};var E=g;
|
package/dist/cjs/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var zt=Object.create;var at=Object.defineProperty;var jt=Object.getOwnPropertyDescriptor;var Bt=Object.getOwnPropertyNames;var Gt=Object.getPrototypeOf,Qt=Object.prototype.hasOwnProperty;var Wt=(t,e)=>{for(var s in e)at(t,s,{get:e[s],enumerable:!0})},Ct=(t,e,s,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Bt(e))!Qt.call(t,o)&&o!==s&&at(t,o,{get:()=>e[o],enumerable:!(r=jt(e,o))||r.enumerable});return t};var Pt=(t,e,s)=>(s=t!=null?zt(Gt(t)):{},Ct(e||!t||!t.__esModule?at(s,"default",{value:t,enumerable:!0}):s,t)),Yt=t=>Ct(at({},"__esModule",{value:!0}),t);var le={};Wt(le,{createAdapter:()=>Xt,default:()=>ue,executeFetch:()=>Dt,fetchPlugin:()=>ce,initAdapterAuth:()=>ht,parseDuration:()=>Y,queryClient:()=>fe,registerAdapter:()=>Ht,resolveDb:()=>Mt});module.exports=Yt(le);var f=require("@symbo.ls/utils");const xt=["select","rpc","insert","update","upsert","delete","subscribe"],Kt={rest:()=>import("./adapters/rest.js"),local:()=>import("./adapters/local.js")},ft=Symbol.for("@symbo.ls/fetch:CUSTOM_ADAPTERS"),V=(()=>{if(typeof globalThis<"u"&&globalThis[ft])return globalThis[ft];const t={};if(typeof globalThis<"u")try{return Object.defineProperty(globalThis,ft,{value:t,writable:!1,configurable:!1,enumerable:!1}),globalThis[ft]}catch{}return t})(),ct=Symbol.for("@symbo.ls/fetch:PENDING_ADAPTERS"),St=(()=>{if(typeof globalThis<"u"&&globalThis[ct])return globalThis[ct];const t={};if(typeof globalThis<"u")try{return Object.defineProperty(globalThis,ct,{value:t,writable:!1,configurable:!1,enumerable:!1}),globalThis[ct]}catch{}return t})(),Jt=5e3,Vt=t=>new Promise(e=>{if(V[t])return e(V[t]);const s=St[t]||=[];let r=!1;const o=()=>{r||(r=!0,e(V[t]||null))};s.push(o),setTimeout(o,Jt)}),Ht=(t,e)=>{V[t]=e;const s=St[t];if(s&&s.length){St[t]=[];for(const r of s)r()}},Xt=t=>{const e={};for(const s of xt)t[s]&&(e[s]=t[s]);return e.name=t.name||"custom",e},Mt=async t=>{if(!t)return null;if(typeof t.select=="function")return t;const{adapter:e,...s}=t,r=typeof e=="string"?e:typeof t=="string"?t:null;if(!r)return null;let o=V[r]||Kt[r];if(!o&&(o=await Vt(r),!o))throw new Error(`Unknown db adapter: "${r}". Use registerAdapter() for adapters with optional deps.`);const n=await o();if(!n||typeof n.setup!="function")throw new Error(`Adapter "${r}" loader returned a module without a setup() function. Got keys: [${Object.keys(n||{}).join(", ")}]. Likely a bundler chunk-resolution issue.`);return n.setup(s)},Y=t=>{if(!t)return 0;if(typeof t=="number")return t;const e=t.match(/^(\d+)(ms|s|m|h)$/);if(!e)return 0;const s=parseInt(e[1]),r=e[2];return r==="ms"?s:r==="s"?s*1e3:r==="m"?s*6e4:r==="h"?s*36e5:0},T=new Map,U=new Map,Q=new Map,Zt=(t,e,s)=>{if(t.cache?.key)return t.cache.key;const r=se(t.params),o=s?`${s}:`:"",n=`${t.from}:${t.method}:${o}${JSON.stringify(r||"")}`;return e?`${n}:${e}`:n},H=t=>T.get(t)||null,X=(t,e,s)=>{const r=T.get(t),o={data:e,error:s,time:Date.now(),stale:!1};T.set(t,o);const n=U.get(t);if(n)for(const a of n)(0,f.isFunction)(a)&&a(o);return o},Z=t=>{if(t){const e=T.get(t);e&&(e.stale=!0);return}for(const[,e]of T)e.stale=!0},ut=t=>{if(t){T.delete(t);return}T.clear()},_e=(t,e)=>(U.has(t)||U.set(t,new Set),U.get(t).add(e),()=>{const s=U.get(t);s&&(s.delete(e),s.size===0&&U.delete(t))}),bt=t=>!t&&t!==!1?{staleTime:6e4,gcTime:3e5}:t===!1?null:t===!0?{staleTime:6e4,gcTime:3e5}:typeof t=="number"?{staleTime:t,gcTime:Math.max(t*5,3e5)}:(0,f.isString)(t)?{staleTime:Y(t),gcTime:3e5}:{staleTime:Y(t.stale||t.staleTime)||6e4,gcTime:Y(t.gc||t.gcTime||t.expire)||3e5,key:t.key};let lt=null;const te=()=>{lt||(lt=setInterval(()=>{const t=Date.now();for(const[e,s]of T){const r=U.get(e);!(r&&r.size>0)&&t-s.time>(s.gcTime||3e5)&&T.delete(e)}},3e4),lt.unref&<.unref())};te();const At=3,wt=t=>Math.min(1e3*2**t,3e4),Lt=t=>{const e=t.retry;return e===!1?{count:0}:e===!0||e===void 0?{count:At,delay:wt}:typeof e=="number"?{count:e,delay:wt}:{count:e.count??At,delay:(0,f.isFunction)(e.delay)?e.delay:typeof e.delay=="number"?()=>e.delay:wt}},Ot=async(t,e)=>{const{count:s,delay:r}=e;let o;for(let n=0;n<=s;n++)try{const a=await t();if(a?.error){if(o=a.error,n<s){const u=(0,f.isFunction)(r)?r(n,o):r;await new Promise(i=>setTimeout(i,u));continue}return a}return a}catch(a){if(o=a,n<s){const u=(0,f.isFunction)(r)?r(n,a):r;await new Promise(i=>setTimeout(i,u));continue}throw a}return{data:null,error:o}},W={focus:new Set,online:new Set};let Rt=!1;const ee=()=>{if(Rt||typeof window>"u")return;Rt=!0;const t=()=>{for(const s of W.focus)s()},e=()=>{for(const s of W.online)s()};window.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&t()}),window.addEventListener("focus",t),window.addEventListener("online",e)},kt=(t,e)=>{const s=e.__ref;if(t===!0)return{from:s.__state||e.key,method:"select",query:!0,on:"create"};if((0,f.isString)(t))return{from:t,method:"select",query:!0,on:"create"};if((0,f.isObject)(t)){const r={...t};return r.from=r.from||s.__state||e.key,r.method=r.method||"select",r.on=r.on||"create",r.query===void 0&&(r.query=!0),r}return null},se=t=>(!t||(0,f.isFunction)(t),t),dt=(t,e)=>{const s=t?.state?.root||e?.state?.root;if(s?.lang)return s.lang},Tt=(t,e)=>{const r=(t?.state?.root||e?.state?.root)?.__fetchScope;return r?String(r):void 0},$t=(t,e,s)=>{let r;if(!t)r=void 0;else if((0,f.isFunction)(t))r=t(e,e.state);else{r={};for(const o in t){const n=t[o];r[o]=(0,f.isFunction)(n)?n(e,e.state):n}}return r},ht=async(t,e)=>{if(!t||t.__authInitialized||(t.__authInitialized=!0,!t.getSession))return;const s=(r,o)=>{const n=e.state?.root;n?.update&&n.update({auth:{user:r,session:o,loading:!1}})};try{const r=await t.getSession();s(r?.user||null,r)}catch(r){console.warn("[fetch] Failed to restore auth session:",r.message)}t.onAuthStateChange&&t.onAuthStateChange((r,o)=>{s(o?.user||null,o)})},mt=async(t,e)=>{if((0,f.isFunction)(t.select))return t.auth!==!1&&await ht(t,e),t;if(t.__resolved)return t.auth!==!1&&await ht(t.__resolved,e),t.__resolved;if(t.__resolving)return t.__resolving;t.__resolving=Mt(t);const s=await t.__resolving;return delete t.__resolving,s?(s.auth=t.auth,s.url=t.url,s.key=t.key,t.__resolved=s,e.fetch=s,t.auth!==!1&&await ht(s,e),s):null},E=(t,e,...s)=>{const r=(0,f.isFunction)(t[e])?t[e]:null;r&&r.call(t,...s,t,t.state,t.context)},A=(t,e,s,...r)=>{const o=t&&(0,f.isFunction)(t[s])?t[s]:null;o&&o.call(e,...r,e,e.state,e.context)},tt=t=>{const e={},s=t.node;if(!s)return e;if(s.tagName==="FORM"){const o=new FormData(s);for(const[n,a]of o.entries())e[n]=a;return e}const r=s.querySelectorAll("input, textarea, select");for(let o=0;o<r.length;o++){const n=r[o],a=n.name||n.getAttribute("name");a&&(n.type==="checkbox"?e[a]=n.checked:n.type==="file"?e[a]=n.files:e[a]=n.value)}return e},vt=t=>t.responseType==="stream"||t.responseType==="response",re=["Blob","File","ArrayBuffer","ReadableStream","Response"],Ft=t=>t!==null&&typeof t=="object"&&(ArrayBuffer.isView(t)||re.includes(Object.prototype.toString.call(t).slice(8,-1))),q=(t,e,s,r={})=>{if(!s&&Ft(e))return;const o=s&&s.startsWith("~/"),n=o&&t.state?.root||t.state;if(n?.update)if(o){const a=s.slice(2);e&&typeof e=="object"&&!Array.isArray(e)&&!Ft(e)&&a in e?n.update(e,{preventFetch:!0,...r}):n.update({[a]:e},{preventFetch:!0,...r})}else{const a=s?{[s]:e}:e;n.update(a,{preventFetch:!0,...r})}},L=(t,e)=>{const s=t?.__ref;s&&(s.__fetchStatus=e,s.__fetching=e.isFetching,s.__fetchError=e.error)},N=async(t,e,s,r={})=>{const o=s?.fetch;if(!o||!e||!e.__ref)return;const n=e.__ref,a=Tt(e,s);(!n.__fetchScopeOwner||n.__fetchScopeOwner.scope!==a)&&(n.__fetchScopeOwner={scope:a});const u=n.__fetchScopeOwner,i=()=>e.__ref===n&&n.__fetchScopeOwner===u&&Tt(e,s)===a;if(t.enabled===!1||(0,f.isFunction)(t.enabled)&&!t.enabled(e,e.state)||t.skip===!0||(0,f.isFunction)(t.skip)&&t.skip(e,e.state))return;const h=await mt(o,s);if(!h||!i())return;const{from:g,method:S,query:R,params:x,cache:et,transform:D,single:z,auth:st,fields:j,as:k,limit:I,offset:$,order:b,headers:K,baseUrl:C,responseType:B,page:p,cursor:P,getNextPageParam:J,getPreviousPageParam:rt,infinite:nt,placeholderData:v,initialData:F,select:m,keepPreviousData:M}=t;let G=(0,f.isString)(m)?m:void 0;if(R&&(0,f.isFunction)(e.getQuery)){const d=e.getQuery(h.name||"paths");d&&(G=d.select||d.length&&d.join(",")||G)}const ot=$t(x,e,s),it=vt(t)?null:bt(et),Nt=Lt(t),pt=dt(e,s),It=pt?`:${pt}`:"",Ut=a?`${a}:`:"",_=it?et?.key||`${g}:${S}:${Ut}${JSON.stringify(ot||"")}${nt?":infinite":""}${p?":p"+JSON.stringify(p):""}${It}`:null;if(!n.__fetchInitialized&&_&&(n.__fetchInitialized=!0,F!==void 0)){const d=(0,f.isFunction)(F)?F():F;X(_,d,null)}if((S==="select"||S==="rpc")&&_&&it){const d=H(_);if(d&&!d.error){const l=Date.now()-d.time,y=d.stale||l>(it.staleTime||0);let c=d.data;if((0,f.isFunction)(m)&&(c=m(c,e,e.state)),D&&(c=D(c,e,e.state)),!i())return;if(q(e,c,k),!y){L(e,{isFetching:!1,isLoading:!1,isStale:!1,isSuccess:!0,error:null,status:"success",fetchStatus:"idle"});return}}else if(v!==void 0){const l=(0,f.isFunction)(v)?v(e,e.state):v;l!==void 0&&q(e,l,k)}}if(_&&Q.has(_)&&!r.force){const d=Q.get(_);try{const l=await Promise.race([d,new Promise((y,c)=>setTimeout(()=>c("DEDUP_TIMEOUT"),15e3))]);if(!i())return;if(l?.data!==void 0){let y=l.data;if((0,f.isFunction)(m)&&(y=m(y,e,e.state)),D&&(y=D(y,e,e.state)),!i())return;q(e,y,k),E(e,"onFetchComplete",y),A(t,e,"onFetchComplete",y)}}catch{if(!i())return}return}const qt=!H(_)?.data;L(e,{isFetching:!0,isLoading:qt,isStale:!1,isSuccess:!1,error:null,status:"pending",fetchStatus:"fetching"}),E(e,"onFetchStart"),A(t,e,"onFetchStart");const O=s?.analyze?.emitNetwork,_t=O?typeof performance<"u"?performance.now():Date.now():0;O&&O({phase:"start",mode:"query",from:g,method:S,cacheKey:_,lang:pt});const yt=Ot(async()=>{if(!i())return;if(st!==!1&&h.auth!==!1&&h.getSession){const c=await h.getSession();if(!i())return;if(st===!0&&!c){const w={message:"Not authenticated"};return L(e,{isFetching:!1,isLoading:!1,isStale:!1,isSuccess:!1,error:w,status:"error",fetchStatus:"idle"}),E(e,"onFetchError",w),A(t,e,"onFetchError",w),{data:null,error:w}}}const d=h[S];if(!(0,f.isFunction)(d))return{data:null,error:{message:`Method "${S}" not found on adapter`}};const l={from:g,select:G,params:ot,single:z,limit:I,offset:$,order:b,headers:K,baseUrl:C};B!==void 0&&(l.responseType=B);const y=dt(e,s);if(y&&(l.headers={...l.headers,"Accept-Language":y}),p!==void 0){if((0,f.isObject)(p))p.offset!==void 0&&(l.offset=p.offset),p.limit!==void 0&&(l.limit=p.limit),p.cursor!==void 0&&(l.params={...l.params,cursor:p.cursor});else if(typeof p=="number"){const c=t.pageSize||I||20;l.offset=(p-1)*c,l.limit=c}}if(P!==void 0&&(l.params={...l.params,cursor:P}),S==="insert"||S==="update"||S==="upsert"){let c;if(j===!0||t.on==="submit")c=tt(e);else if((0,f.isArray)(j)){const w=tt(e);c={};for(const gt of j)c[gt]=w[gt]}else e.state?.parse?c=e.state.parse():(0,f.isObject)(e.state)&&(c={...e.state});D&&(c=D(c,e,e.state)),l.data=c}if(S==="rpc"){let c=ot;if(t.on==="submit"){const w=tt(e);c=t.transformParams?t.transformParams(w,e,e.state):w}l.params=c}if(S==="subscribe"){const c=h.subscribe({from:g,params:ot,on:t.subscribeOn},(w,gt,he)=>{i()&&(q(e,w,k),E(e,"onFetchComplete",w),A(t,e,"onFetchComplete",w))});return i()?(n.__unsubscribe=c,{data:null,error:null,subscribed:!0}):((0,f.isFunction)(c)&&c(),{data:null,error:null,subscribed:!0})}return d(l)},Nt);_&&Q.set(_,yt);try{const d=await yt;if(!i()||d?.subscribed)return;const{data:l,error:y}=d||{};if(y){_&&X(_,null,y),L(e,{isFetching:!1,isLoading:!1,isStale:!1,isSuccess:!1,error:y,status:"error",fetchStatus:"idle"}),E(e,"onFetchError",y),A(t,e,"onFetchError",y),O&&O({phase:"error",mode:"query",from:g,method:S,cacheKey:_,error:y.message||y,durationMs:(typeof performance<"u"?performance.now():Date.now())-_t});return}if(l!==void 0){if((S==="select"||S==="rpc")&&_){const w=X(_,l,null);w.gcTime=it?.gcTime||3e5}let c=l;if(nt&&(0,f.isArray)(l)&&(n.__pages||(n.__pages=[]),r.direction==="previous"?n.__pages.unshift(l):n.__pages.push(l),c=n.__pages.flat(),J&&(n.__nextPageParam=J(l,n.__pages),n.__hasNextPage=n.__nextPageParam!=null),rt&&(n.__prevPageParam=rt(l,n.__pages),n.__hasPreviousPage=n.__prevPageParam!=null)),(0,f.isFunction)(m)&&(c=m(c,e,e.state)),D&&(c=D(c,e,e.state)),!i())return;(!M||c!==void 0)&&q(e,c,k),L(e,{isFetching:!1,isLoading:!1,isStale:!1,isSuccess:!0,error:null,status:"success",fetchStatus:"idle"}),E(e,"onFetchComplete",c),A(t,e,"onFetchComplete",c),O&&O({phase:"success",mode:"query",ok:!0,from:g,method:S,cacheKey:_,durationMs:(typeof performance<"u"?performance.now():Date.now())-_t})}}catch(d){if(!i())return;L(e,{isFetching:!1,isLoading:!1,isStale:!1,isSuccess:!1,error:d,status:"error",fetchStatus:"idle"}),E(e,"onFetchError",d),A(t,e,"onFetchError",d),O&&O({phase:"error",mode:"query",from:g,method:S,cacheKey:_,error:d.message||String(d),durationMs:(typeof performance<"u"?performance.now():Date.now())-_t})}finally{_&&Q.get(_)===yt&&Q.delete(_)}},ne=(t,e,s)=>{const r=t.on,o=e.__ref;o.__fetchListeners||(o.__fetchListeners=[]);const n=t.__runner||N;if(r==="submit"){const a=i=>{i.preventDefault(),n(t,e,s)},u=e.node;u&&(u.addEventListener("submit",a),o.__fetchListeners.push(()=>u.removeEventListener("submit",a)))}else if(r==="click"){const a=()=>n(t,e,s),u=e.node;u&&(u.addEventListener("click",a),o.__fetchListeners.push(()=>u.removeEventListener("click",a)))}else r==="stateChange"&&(o.__fetchOnStateChange=()=>n(t,e,s))},oe=(t,e,s)=>{const r=e.__ref;r.__fetchCleanups||(r.__fetchCleanups=[]),ee();const o=t.refetchInterval;if(o){const i=typeof o=="number"?o:Y(o);if(i>0){const h=setInterval(()=>{(t.refetchIntervalInBackground||typeof document>"u"||document.visibilityState==="visible")&&N(t,e,s,{force:!0})},i);r.__fetchCleanups.push(()=>clearInterval(h))}}const n=vt(t),a=t.refetchOnWindowFocus===void 0?!n:t.refetchOnWindowFocus!==!1,u=t.refetchOnReconnect===void 0?!n:t.refetchOnReconnect!==!1;if(a){const i=()=>{const h=dt(e,s),g=Tt(e,s),S=Zt(t,h,g),R=H(S),x=bt(t.cache);(!R||R.stale||Date.now()-R.time>(x?.staleTime||0))&&N(t,e,s,{force:!0})};W.focus.add(i),r.__fetchCleanups.push(()=>W.focus.delete(i))}if(u){const i=()=>N(t,e,s,{force:!0});W.online.add(i),r.__fetchCleanups.push(()=>W.online.delete(i))}},ie=(t,e,s)=>{if(!e.optimistic)return null;const r=t.__ref,o=e.as,n=t.state?.parse?t.state.parse():(0,f.isObject)(t.state)?{...t.state}:t.state;r.__optimisticSnapshot=n;const a=(0,f.isFunction)(e.optimistic)?e.optimistic(s,n,t):e.optimistic;return a!==void 0&&q(t,a,o),n},Et=(t,e)=>{const s=t.__ref,r=s.__optimisticSnapshot;r!==void 0&&(q(t,r,e.as),delete s.__optimisticSnapshot)},ae=async(t,e,s)=>{const r=s?.fetch;if(!r)return;const o=await mt(r,s);if(!o)return;const n=e.__ref,{method:a,from:u,fields:i,transform:h,as:g,on:S,auth:R,headers:x,baseUrl:et,responseType:D,invalidates:z,optimistic:st,onMutate:j,onSuccess:k,onError:I,onSettled:$}=t;let b;if(i===!0||S==="submit")b=tt(e);else if((0,f.isArray)(i)){const p=tt(e);b={};for(const P of i)b[P]=p[P]}else e.state?.parse?b=e.state.parse():(0,f.isObject)(e.state)&&(b={...e.state});h&&(b=h(b,e,e.state)),(0,f.isFunction)(j)&&j(b,e,e.state);const K=st?ie(e,t,b):null;n.__fetching=!0,L(e,{isFetching:!0,isLoading:!1,isStale:!1,isSuccess:!1,error:null,status:"pending",fetchStatus:"fetching"}),E(e,"onFetchStart"),A(t,e,"onFetchStart");const C=s?.analyze?.emitNetwork,B=C?typeof performance<"u"?performance.now():Date.now():0;C&&C({phase:"start",mode:"mutation",from:u,method:a});try{if(R!==!1&&o.auth!==!1&&o.getSession){const m=await o.getSession();if(R===!0&&!m){K!==void 0&&Et(e,t);const M={message:"Not authenticated"};E(e,"onFetchError",M),A(t,e,"onFetchError",M);return}}const p=o[a];if(!(0,f.isFunction)(p))return;const P={from:u,data:b,headers:x,baseUrl:et};D!==void 0&&(P.responseType=D),t.params&&(P.params=$t(t.params,e,s));const J=dt(e,s);J&&(P.headers={...P.headers,"Accept-Language":J});const rt=Lt(t),nt=await Ot(()=>p(P),rt),{data:v,error:F}=nt||{};if(F){K!==void 0&&Et(e,t),L(e,{isFetching:!1,isLoading:!1,isStale:!1,isSuccess:!1,error:F,status:"error",fetchStatus:"idle"}),E(e,"onFetchError",F),(0,f.isFunction)(I)&&I(F,b,e),(0,f.isFunction)($)&&$(null,F,b,e),C&&C({phase:"error",mode:"mutation",from:u,method:a,error:F.message||String(F),durationMs:(typeof performance<"u"?performance.now():Date.now())-B});return}if(delete n.__optimisticSnapshot,v!==void 0&&(g||!Ft(v))){const m=g?{[g]:v}:v;e.state?.update&&e.state.update(m,{preventFetch:!0})}if(L(e,{isFetching:!1,isLoading:!1,isStale:!1,isSuccess:!0,error:null,status:"success",fetchStatus:"idle"}),E(e,"onFetchComplete",v),A(t,e,"onFetchComplete",v),(0,f.isFunction)(k)&&k(v,b,e),(0,f.isFunction)($)&&$(v,null,b,e),C&&C({phase:"success",mode:"mutation",ok:!0,from:u,method:a,durationMs:(typeof performance<"u"?performance.now():Date.now())-B}),z){const m=(0,f.isArray)(z)?z:[z];for(const M of m)if(M===!0||M==="*")for(const[G]of T)G.startsWith(u+":")&&Z(G);else Z(M)}}catch(p){K!==void 0&&Et(e,t),L(e,{isFetching:!1,isLoading:!1,isStale:!1,isSuccess:!1,error:p,status:"error",fetchStatus:"idle"}),E(e,"onFetchError",p),A(t,e,"onFetchError",p),(0,f.isFunction)(I)&&I(p,b,e),(0,f.isFunction)($)&&$(null,p,b,e),C&&C({phase:"error",mode:"mutation",from:u,method:a,error:p.message||String(p),durationMs:(typeof performance<"u"?performance.now():Date.now())-B})}finally{n.__fetching=!1}},Dt=(t,e,s,r)=>{if(!t||!r?.fetch)return;const n=(0,f.exec)(t,e);if(!n)return;const a=(0,f.isArray)(n)?n.map(i=>kt((0,f.exec)(i,e),e)).filter(Boolean):[kt(n,e)].filter(Boolean);for(const i of a){const h=i.method==="insert"||i.method==="update"||i.method==="upsert"||i.method==="delete",g=h?ae:N;i.on==="create"?g(i,e,r):Promise.resolve().then(()=>{ne({...i,__runner:g},e,r)}),!h&&i.on==="create"&&(i.refetchInterval||i.refetchOnWindowFocus!==!1||i.refetchOnReconnect!==!1)&&oe(i,e,r)}const u=e.__ref;u.refetch=i=>{for(const h of a)N(h,e,r,{force:!0,...i})},u.fetchNextPage=()=>{const i=a[0];if(!i||!i.infinite)return;const h=u.__nextPageParam;if(h==null)return;const g={...i,cursor:h};N(g,e,r,{direction:"next",force:!0})},u.fetchPreviousPage=()=>{const i=a[0];if(!i||!i.infinite)return;const h=u.__prevPageParam;if(h==null)return;const g={...i,cursor:h};N(g,e,r,{direction:"previous",force:!0})}},fe={invalidateQueries:t=>{if(!t){Z();return}if((0,f.isString)(t))for(const[e]of T)(e.startsWith(t)||e.includes(t))&&Z(e);else if((0,f.isArray)(t)){const e=t.join(":");for(const[s]of T)s.includes(e)&&Z(s)}},removeQueries:t=>{if(!t){ut();return}if((0,f.isString)(t))for(const[e]of T)(e.startsWith(t)||e.includes(t))&&ut(e)},getQueryData:t=>H(t)?.data??void 0,setQueryData:(t,e)=>{const s=H(t),r=(0,f.isFunction)(e)?e(s?.data):e;X(t,r,null)},prefetchQuery:async(t,e)=>{const s=e?.fetch;if(!s)return;const r=await mt(s,e);if(!r)return;const o=t.cache?.key||`${t.from}:${t.method||"select"}:${JSON.stringify(t.params||"")}`,n=r[t.method||"select"];if(!(0,f.isFunction)(n))return;const a={from:t.from,params:t.params,limit:t.limit,offset:t.offset,order:t.order,single:t.single,headers:t.headers,baseUrl:t.baseUrl};t.responseType!==void 0&&(a.responseType=t.responseType);const u=await n(a);if(u?.data!==void 0&&!u?.error&&!vt(t)){const i=X(o,u.data,null);i.gcTime=bt(t.cache)?.gcTime||3e5}return u},getCache:()=>T,clear:()=>ut(),dropNonLang:t=>{if(!t)return;const e=`:${t}`;for(const[s]of T)s.match(/:([a-z]{2,3})$/i)&&(s.endsWith(e)||ut(s))}},ce={name:"fetch",create(t){const e=t.fetch;e&&(t.parent||Q.clear(),Dt(e,t,t.state,t.context))}};var ue=Dt;
|
|
1
|
+
"use strict";var ct=Object.create;var he=Object.defineProperty;var ft=Object.getOwnPropertyDescriptor;var lt=Object.getOwnPropertyNames;var dt=Object.getPrototypeOf,pt=Object.prototype.hasOwnProperty;var ht=(e,t)=>{for(var r in t)he(e,r,{get:t[r],enumerable:!0})},Be=(e,t,r,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of lt(t))!pt.call(e,o)&&o!==r&&he(e,o,{get:()=>t[o],enumerable:!(s=ft(t,o))||s.enumerable});return e};var Ge=(e,t,r)=>(r=e!=null?ct(dt(e)):{},Be(t||!e||!e.__esModule?he(r,"default",{value:e,enumerable:!0}):r,e)),_t=e=>Be(he({},"__esModule",{value:!0}),e);var Ut={};ht(Ut,{createAdapter:()=>Tt,default:()=>Nt,executeFetch:()=>$e,fetchFunctions:()=>It,fetchPlugin:()=>qt,hasAdapter:()=>wt,initAdapterAuth:()=>Fe,parseDuration:()=>ee,queryClient:()=>ie,registerAdapter:()=>gt,resolveDb:()=>ot});module.exports=_t(Ut);var i=require("@symbo.ls/utils"),st=require("@symbo.ls/signal"),nt=require("./early.js");const yt=["select","rpc","insert","update","upsert","delete","subscribe"],Ke={rest:()=>import("./adapters/rest.js"),local:()=>import("./adapters/local.js")},_e=Symbol.for("@symbo.ls/fetch:CUSTOM_ADAPTERS"),X=(()=>{if(typeof globalThis<"u"&&globalThis[_e])return globalThis[_e];const e={};if(typeof globalThis<"u")try{return Object.defineProperty(globalThis,_e,{value:e,writable:!1,configurable:!1,enumerable:!1}),globalThis[_e]}catch{}return e})(),ye=Symbol.for("@symbo.ls/fetch:PENDING_ADAPTERS"),Ae=(()=>{if(typeof globalThis<"u"&&globalThis[ye])return globalThis[ye];const e={};if(typeof globalThis<"u")try{return Object.defineProperty(globalThis,ye,{value:e,writable:!1,configurable:!1,enumerable:!1}),globalThis[ye]}catch{}return e})(),St=5e3,bt=e=>new Promise(t=>{if(X[e])return t(X[e]);const r=Ae[e]||=[];let s=!1;const o=()=>{s||(s=!0,t(X[e]||null))};r.push(o),setTimeout(o,St)}),gt=(e,t)=>{X[e]=t;const r=Ae[e];if(r&&r.length){Ae[e]=[];for(const s of r)s()}},wt=e=>typeof e=="string"&&!!(X[e]||Ke[e]),Tt=e=>{const t={};for(const r of yt)e[r]&&(t[r]=e[r]);return t.name=e.name||"custom",t},ot=async e=>{if(!e)return null;if(typeof e.select=="function")return e;const{adapter:t,...r}=e,s=typeof t=="string"?t:typeof e=="string"?e:null;if(!s)return null;let o=X[s]||Ke[s];if(!o&&(o=await bt(s),!o))throw new Error(`Unknown db adapter: "${s}". Use registerAdapter() for adapters with optional deps.`);const n=await o();if(!n||typeof n.setup!="function")throw new Error(`Adapter "${s}" loader returned a module without a setup() function. Got keys: [${Object.keys(n||{}).join(", ")}]. Likely a bundler chunk-resolution issue.`);return n.setup(r)},ee=e=>{if(!e)return 0;if(typeof e=="number")return e;const t=e.match(/^(\d+)(ms|s|m|h)$/);if(!t)return 0;const r=parseInt(t[1]),s=t[2];return s==="ms"?r:s==="s"?r*1e3:s==="m"?r*6e4:s==="h"?r*36e5:0},v=new Map,K=new Map,R=new Map;let I=0;const q=new Map,Ce=new WeakMap,Me=(e,t,r,s,o=e.page,n=e.cursor)=>{if(e.cache?.key)return e.cache.key;const{from:u,method:c,infinite:a}=e,d=r?`${r}:`:"",_=s?`:${s}`:"",h=o?":p"+JSON.stringify(o):"",D=n!=null?":c"+JSON.stringify(n):"";return`${u}:${c}:${d}${JSON.stringify(t||"")}${a?":infinite":""}${h}${D}${_}`},re=e=>v.get(e)||null,se=(e,t,r,s=++I,o=!1)=>{const n={data:t,error:r,time:Date.now(),stale:o,seq:s};v.set(e,n);const u=K.get(e);if(u)for(const c of u)(0,i.isFunction)(c)&&c(n);return n},Se=(e,t)=>{const r=e?v.get(e):null;return r&&!r.error&&r.seq>t?r:null},Le=(e,t)=>(q.get(e)||0)>t,be=e=>{if(e){v.delete(e),q.set(e,++I);return}for(const[t]of v)q.set(t,++I);for(const[t]of R)q.set(t,++I);v.clear()},$t=(e,t)=>(K.has(e)||K.set(e,new Set),K.get(e).add(t),()=>{const r=K.get(e);r&&(r.delete(t),r.size===0&&K.delete(e))}),ke=e=>!e&&e!==!1?{staleTime:6e4,gcTime:3e5}:e===!1?null:e===!0?{staleTime:6e4,gcTime:3e5}:typeof e=="number"?{staleTime:e,gcTime:Math.max(e*5,3e5)}:(0,i.isString)(e)?{staleTime:ee(e),gcTime:3e5}:{staleTime:ee(e.stale||e.staleTime)||6e4,gcTime:ee(e.gc||e.gcTime||e.expire)||3e5,key:e.key},x=new Set,xe=e=>!!e.ref&&e.element.__ref===e.ref,vt=({config:e,element:t,context:r})=>{try{return Ie(e,t,r)}catch{return null}};let ge=null;const Ft=()=>{ge||(ge=setInterval(()=>{const e=Date.now();for(const[t,r]of v){const s=K.get(t);!(s&&s.size>0)&&e-r.time>(r.gcTime||3e5)&&v.delete(t)}for(const[t]of q)!v.has(t)&&!R.has(t)&&q.delete(t);for(const t of x)xe(t)||x.delete(t)},3e4),ge.unref&&ge.unref())};Ft();const Ve=3,Oe=e=>Math.min(1e3*2**e,3e4),We=(e,t)=>{const r=e.retry;return r===void 0&&t?{count:0}:r===!1?{count:0}:r===!0||r===void 0?{count:Ve,delay:Oe}:typeof r=="number"?{count:r,delay:Oe}:{count:r.count??Ve,delay:(0,i.isFunction)(r.delay)?r.delay:typeof r.delay=="number"?()=>r.delay:Oe}},Ye=async(e,t)=>{const{count:r,delay:s}=t;let o;for(let n=0;n<=r;n++)try{const u=await e();if(u?.error){if(o=u.error,n<r){const c=(0,i.isFunction)(s)?s(n,o):s;await new Promise(a=>setTimeout(a,c));continue}return u}return u}catch(u){if(o=u,n<r){const c=(0,i.isFunction)(s)?s(n,u):s;await new Promise(a=>setTimeout(a,c));continue}throw u}return{data:null,error:o}},Z={focus:new Set,online:new Set};let Je=!1;const Et=()=>{if(Je||typeof window>"u")return;Je=!0;const e=()=>{for(const r of Z.focus)r()},t=()=>{for(const r of Z.online)r()};window.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&e()}),window.addEventListener("focus",e),window.addEventListener("online",t)},He=(e,t)=>{const r=t.__ref;if(e===!0)return{from:r.__state||t.key,method:"select",query:!0,on:"create"};if((0,i.isString)(e))return{from:e,method:"select",query:!0,on:"create"};if((0,i.isObject)(e)){const s={...e};return s.from=s.from||r.__state||t.key,s.method=s.method||"select",s.on=s.on||"create",s.query===void 0&&(s.query=!0),s}return null},Dt=["insert","update","upsert","delete"],Xe=e=>Dt.includes(e),Re=e=>e.mutation===!0?!0:e.mutation===!1||e.method!=="rpc"?!1:e.on==="submit"||e.on==="click"||e.invalidates!=null,ne=(e,t)=>{const r=e?.state?.root||t?.state?.root;if(r?.lang)return r.lang},we=(e,t)=>{const s=(e?.state?.root||t?.state?.root)?.__fetchScope;return s?String(s):void 0},Te=(e,t,r)=>{let s;if(!e)s=void 0;else if((0,i.isFunction)(e))s=e(t,t.state);else{s={};for(const o in e){const n=e[o];s[o]=(0,i.isFunction)(n)?n(t,t.state):n}}return s},oe=(e,t)=>(0,i.isFunction)(e)?e(t,t.state):e,Ie=(e,t,r)=>Me(e,Te(e.params,t,r),we(t,r),ne(t,r),oe(e.page,t),oe(e.cursor,t)),Fe=async(e,t)=>{if(!e||e.__authInitialized||(e.__authInitialized=!0,!e.getSession))return;const r=(s,o)=>{const n=t.state?.root;n?.update&&n.update({auth:{user:s,session:o,loading:!1}})};try{const s=await e.getSession();r(s?.user||null,s)}catch(s){console.warn("[fetch] Failed to restore auth session:",s.message)}e.onAuthStateChange&&e.onAuthStateChange((s,o)=>{r(o?.user||null,o)})},qe=async(e,t)=>{if((0,i.isFunction)(e.select))return e.auth!==!1&&await Fe(e,t),e;if(e.__resolved)return e.auth!==!1&&await Fe(e.__resolved,t),e.__resolved;if(e.__resolving)return e.__resolving;e.__resolving=ot(e);const r=await e.__resolving;return delete e.__resolving,r?(r.auth=e.auth,r.url=e.url,r.key=e.key,e.__resolved=r,t.fetch=r,e.auth!==!1&&await Fe(r,t),r):null},F=(e,t,...r)=>{const s=(0,i.isFunction)(e[t])?e[t]:null;s&&s.call(e,...r,e,e.state,e.context)},E=(e,t,r,...s)=>{const o=e&&(0,i.isFunction)(e[r])?e[r]:null;o&&o.call(t,...s,t,t.state,t.context)},ae=e=>{const t={},r=e.node;if(!r)return t;if(r.tagName==="FORM"){const o=new FormData(r);for(const[n,u]of o.entries())t[n]=u;return t}const s=r.querySelectorAll("input, textarea, select");for(let o=0;o<s.length;o++){const n=s[o],u=n.name||n.getAttribute("name");u&&(n.type==="checkbox"?t[u]=n.checked:n.type==="file"?t[u]=n.files:t[u]=n.value)}return t},ve=e=>e.responseType==="stream"||e.responseType==="response",Pt=["Blob","File","ArrayBuffer","ReadableStream","Response"],Ne=e=>e!==null&&typeof e=="object"&&(ArrayBuffer.isView(e)||Pt.includes(Object.prototype.toString.call(e).slice(8,-1))),Q=(e,t,r,s={})=>{if(!r&&Ne(t))return;const o=r&&r.startsWith("~/"),n=o&&e.state?.root||e.state;if(n?.update)if(o){const u=r.slice(2);t&&typeof t=="object"&&!Array.isArray(t)&&!Ne(t)&&u in t?n.update(t,{preventFetch:!0,...s}):n.update({[u]:t},{preventFetch:!0,...s})}else{const u=r?{[r]:t}:t;n.update(u,{preventFetch:!0,...s})}},C=(e,t)=>{const r=e?.__ref;r&&(r.__fetchStatus={...t,isError:!!t.error},r.__fetching=t.isFetching,r.__fetchError=t.error)},Ze=(e,t,r)=>{const s=e.__pages&&e.__pages.length?e.__pages:[r];(0,i.isFunction)(t.getNextPageParam)&&(e.__nextPageParam=t.getNextPageParam(s[s.length-1],s),e.__hasNextPage=e.__nextPageParam!=null),(0,i.isFunction)(t.getPreviousPageParam)&&(e.__prevPageParam=t.getPreviousPageParam(s[0],s),e.__hasPreviousPage=e.__prevPageParam!=null)},N=async(e,t,r,s={})=>{const o=r?.fetch;if(!o||!t||!t.__ref)return;const n=t.__ref,u=we(t,r);(!n.__fetchScopeOwner||n.__fetchScopeOwner.scope!==u)&&(n.__fetchScopeOwner={scope:u});const c=n.__fetchScopeOwner,a=()=>t.__ref===n&&n.__fetchScopeOwner===c&&we(t,r)===u;if(e.enabled===!1||(0,i.isFunction)(e.enabled)&&!e.enabled(t,t.state)||e.skip===!0||(0,i.isFunction)(e.skip)&&e.skip(t,t.state))return;const d=await qe(o,r);if(!d||!a())return;const{from:_,method:h,query:D,params:Ee,cache:De,transform:P,single:ue,auth:ce,fields:V,as:L,limit:$,offset:U,order:b,headers:te,baseUrl:m,responseType:W,page:T,cursor:M,infinite:z,placeholderData:Y,initialData:J,select:g,keepPreviousData:k}=e;let j=(0,i.isString)(g)?g:void 0;if(D&&(0,i.isFunction)(t.getQuery)){const p=t.getQuery(d.name||"paths");p&&(j=p.select||p.length&&p.join(",")||j)}const B=Te(Ee,t,r),A=oe(T,t),Pe=oe(M,t),fe=Re(e),le=ve(e)||fe?null:ke(De),at=We(e,fe||Xe(h)),ze=ne(t,r),y=le?Me(e,B,u,ze,A,Pe):null;if(!n.__fetchInitialized&&y&&(n.__fetchInitialized=!0,J!==void 0)){const p=(0,i.isFunction)(J)?J():J;se(y,p,null)}if((h==="select"||h==="rpc")&&y&&le&&!s.refresh&&!s.force){const p=re(y);if(p&&!p.error){const f=Date.now()-p.time,w=p.stale||f>(le.staleTime||0);z&&(0,i.isArray)(p.data)&&!n.__pages&&(n.__pages=[p.data],Ze(n,e,p.data));let l=p.data;if((0,i.isFunction)(g)&&(l=g(l,t,t.state)),P&&(l=P(l,t,t.state)),!a())return;if(!w){C(t,{isFetching:!1,isLoading:!1,isStale:!1,isSuccess:!0,error:null,status:"success",fetchStatus:"idle"}),Q(t,l,L);return}Q(t,l,L)}else if(Y!==void 0){const f=(0,i.isFunction)(Y)?Y(t,t.state):Y;f!==void 0&&Q(t,f,L)}}const de=y&&!s.force?R.get(y):null;if(de&&!Le(y,Ce.get(de)||0)){const p=f=>{C(t,{isFetching:!1,isLoading:!1,isStale:!1,isSuccess:!1,error:f,status:"error",fetchStatus:"idle"}),F(t,"onFetchError",f),E(e,t,"onFetchError",f)};try{const f=await Promise.race([de,new Promise((w,l)=>setTimeout(()=>l("DEDUP_TIMEOUT"),15e3))]);if(!a())return;if(f?.error)p(f.error);else if(f?.data!==void 0){const w=!z&&Se(y,Ce.get(de)||0);let l=w?w.data:f.data;if((0,i.isFunction)(g)&&(l=g(l,t,t.state)),P&&(l=P(l,t,t.state)),!a())return;Q(t,l,L),F(t,"onFetchComplete",l),E(e,t,"onFetchComplete",l)}}catch(f){if(!a())return;f!=="DEDUP_TIMEOUT"&&p(f)}return}const it=!re(y)?.data;C(t,{isFetching:!0,isLoading:it,isStale:!1,isSuccess:!1,error:null,status:"pending",fetchStatus:"fetching"}),F(t,"onFetchStart"),E(e,t,"onFetchStart");const O=r?.analyze?.emitNetwork,me=O?typeof performance<"u"?performance.now():Date.now():0;O&&O({phase:"start",mode:"query",from:_,method:h,cacheKey:y,lang:ze});const ut=async()=>{if(!a())return;if(ce!==!1&&d.auth!==!1&&d.getSession){const l=await d.getSession();if(!a())return;if(ce===!0&&!l){const S={message:"Not authenticated"};return C(t,{isFetching:!1,isLoading:!1,isStale:!1,isSuccess:!1,error:S,status:"error",fetchStatus:"idle"}),F(t,"onFetchError",S),E(e,t,"onFetchError",S),{data:null,error:S}}}const p=d[h];if(!(0,i.isFunction)(p))return{data:null,error:{message:`Method "${h}" not found on adapter`}};const f={from:_,select:j,params:B,single:ue,limit:$,offset:U,order:b,headers:te,baseUrl:m};W!==void 0&&(f.responseType=W);const w=ne(t,r);if(w&&(f.headers={...f.headers,"Accept-Language":w}),A!==void 0){if((0,i.isObject)(A))A.offset!==void 0&&(f.offset=A.offset),A.limit!==void 0&&(f.limit=A.limit),A.cursor!==void 0&&(f.params={...f.params,cursor:A.cursor});else if(typeof A=="number"){const l=e.pageSize||$||20;f.offset=(A-1)*l,f.limit=l}}if(Pe!==void 0&&(f.params={...f.params,cursor:Pe}),h==="insert"||h==="update"||h==="upsert"){let l;if(V===!0||e.on==="submit")l=ae(t);else if((0,i.isArray)(V)){const S=ae(t);l={};for(const G of V)l[G]=S[G]}else t.state?.parse?l=t.state.parse():(0,i.isObject)(t.state)&&(l={...t.state});P&&(l=P(l,t,t.state)),f.data=l}if(h==="rpc"){let l=B;if(e.on==="submit"){const S=ae(t);l=e.transformParams?e.transformParams(S,t,t.state):S}f.params=l,f.read=!fe&&e.read!==!1}if(h==="subscribe"){if((0,i.isFunction)(n.__unsubscribe)){const S=n.__unsubscribe;n.__unsubscribe=null;try{S()}catch{}}const l=d.subscribe({from:_,params:B,on:e.subscribeOn},(S,G,je)=>{a()&&(Q(t,S,L),F(t,"onFetchComplete",S),E(e,t,"onFetchComplete",S))});return a()?(n.__unsubscribe=l,{data:null,error:null,subscribed:!0}):((0,i.isFunction)(l)&&l(),{data:null,error:null,subscribed:!0})}return p(f)},H=++I,pe=Ye(ut,at);Ce.set(pe,H),y&&R.set(y,pe);try{const p=await pe;if(fe&&e.invalidates&&p&&!p.error&&!p.subscribed&&tt(e.invalidates,_),!a()||p?.subscribed)return;const{data:f,error:w}=p||{};if(w){y&&!Se(y,H)&&se(y,null,w,H),C(t,{isFetching:!1,isLoading:!1,isStale:!1,isSuccess:!1,error:w,status:"error",fetchStatus:"idle"}),F(t,"onFetchError",w),E(e,t,"onFetchError",w),O&&O({phase:"error",mode:"query",from:_,method:h,cacheKey:y,error:w.message||w,durationMs:(typeof performance<"u"?performance.now():Date.now())-me});return}if(f!==void 0){let l=f;if((h==="select"||h==="rpc")&&y){const G=!z&&Se(y,H);if(G)l=G.data;else{const je=se(y,f,null,H,Le(y,H));je.gcTime=le?.gcTime||3e5}}let S=l;if(z&&(0,i.isArray)(f)&&((!n.__pages||!s.direction)&&(n.__pages=[]),s.direction==="previous"?n.__pages.unshift(f):n.__pages.push(f),S=n.__pages.flat(),Ze(n,e,f)),(0,i.isFunction)(g)&&(S=g(S,t,t.state)),P&&(S=P(S,t,t.state)),!a())return;C(t,{isFetching:!1,isLoading:!1,isStale:!1,isSuccess:!0,error:null,status:"success",fetchStatus:"idle"}),(!k||S!==void 0)&&Q(t,S,L),F(t,"onFetchComplete",S),E(e,t,"onFetchComplete",S),O&&O({phase:"success",mode:"query",ok:!0,from:_,method:h,cacheKey:y,durationMs:(typeof performance<"u"?performance.now():Date.now())-me})}}catch(p){if(!a())return;C(t,{isFetching:!1,isLoading:!1,isStale:!1,isSuccess:!1,error:p,status:"error",fetchStatus:"idle"}),F(t,"onFetchError",p),E(e,t,"onFetchError",p),O&&O({phase:"error",mode:"query",from:_,method:h,cacheKey:y,error:p.message||String(p),durationMs:(typeof performance<"u"?performance.now():Date.now())-me})}finally{y&&R.get(y)===pe&&R.delete(y)}},mt=(e,t,r)=>{const s=e.on,o=t.__ref;if(!o)return;o.__fetchListeners||(o.__fetchListeners=[]);const n=e.__runner||N;if(s==="submit"){const u=a=>{a.preventDefault(),n(e,t,r)},c=t.node;c&&(c.addEventListener("submit",u),o.__fetchListeners.push(()=>c.removeEventListener("submit",u)))}else if(s==="click"){const u=()=>n(e,t,r),c=t.node;c&&(c.addEventListener("click",u),o.__fetchListeners.push(()=>c.removeEventListener("click",u)))}else s==="stateChange"&&At(e,t,r,n)},At=(e,t,r,s)=>{const o=t.__ref;let n;const u=(0,st.createEffect)(()=>{let c;try{c=JSON.stringify([Te(e.params,t,r)??null,(0,i.isFunction)(e.enabled)?!!e.enabled(t,t.state):e.enabled!==!1,(0,i.isFunction)(e.skip)?!!e.skip(t,t.state):e.skip===!0,oe(e.page,t)??null])}catch{return}if(n===void 0){n=c;return}c!==n&&(n=c,Promise.resolve().then(()=>s(e,t,r)))});Array.isArray(o.__effects)?o.__effects.push(u):o.__fetchListeners.push(()=>u.dispose())},Ct=(e,t,r)=>{const s=t.__ref;s.__fetchCleanups||(s.__fetchCleanups=[]),Et();const o=e.refetchInterval;if(o){const a=typeof o=="number"?o:ee(o);if(a>0){const d=setInterval(()=>{(e.refetchIntervalInBackground||typeof document>"u"||document.visibilityState==="visible")&&N(e,t,r,{force:!0})},a);s.__fetchCleanups.push(()=>clearInterval(d))}}const n=ve(e),u=e.refetchOnWindowFocus===void 0?!n:e.refetchOnWindowFocus!==!1,c=e.refetchOnReconnect===void 0?!n:e.refetchOnReconnect!==!1;if(u){const a=()=>{const d=Ie(e,t,r),_=re(d),h=ke(e.cache);(!_||_.stale||Date.now()-_.time>(h?.staleTime||0))&&N(e,t,r,{force:!0})};Z.focus.add(a),s.__fetchCleanups.push(()=>Z.focus.delete(a))}if(c){const a=()=>N(e,t,r,{force:!0});Z.online.add(a),s.__fetchCleanups.push(()=>Z.online.delete(a))}},Mt=(e,t,r)=>{if(!t.optimistic)return null;const s=e.__ref,o=t.as,n=e.state?.parse?e.state.parse():(0,i.isObject)(e.state)?{...e.state}:e.state;s.__optimisticSnapshot=n;const u=(0,i.isFunction)(t.optimistic)?t.optimistic(r,n,e):t.optimistic;return u!==void 0&&Q(e,u,o),n},Ue=(e,t)=>{const r=e.__ref;if(!r||!t.optimistic)return;const s=r.__optimisticSnapshot;s!==void 0&&(Q(e,s,t.as),delete r.__optimisticSnapshot)},Qe=e=>{if(!e)return()=>!0;if((0,i.isString)(e))return t=>t.includes(e);if((0,i.isArray)(e)){const t=e.join(":");return r=>r.includes(t)}return e instanceof RegExp?t=>(e.lastIndex=0,e.test(t)):(0,i.isFunction)(e)?t=>{try{return!!e(t)}catch{return!1}}:()=>!1},Lt=e=>{const t=[];for(const r of x){if(!xe(r)){x.delete(r);continue}const s=vt(r);s&&e(s)&&t.push(N(r.config,r.element,r.context,{refresh:!0}))}return Promise.allSettled(t).then(()=>{})},et=e=>{(0,nt.dropEarly)();for(const[t,r]of v)e(t)&&(r.stale=!0,q.set(t,++I));for(const[t]of R)!v.has(t)&&e(t)&&q.set(t,++I);return Lt(e)},tt=(e,t)=>{const r=((0,i.isArray)(e)?e:[e]).map(s=>s===!0||s==="*"?o=>o.startsWith(t+":"):s?Qe(s):()=>!1);return et(s=>r.some(o=>o(s)))},kt=e=>{for(const[t]of v)e(t)&&be(t);for(const[t]of R)e(t)&&q.set(t,++I)},Ot=async(e,t,r)=>{const s=r?.fetch;if(!s)return;const o=await qe(s,r);if(!o)return;const n=t.__ref,{method:u,from:c,fields:a,transform:d,as:_,on:h,auth:D,headers:Ee,baseUrl:De,responseType:P,invalidates:ue,optimistic:ce,onMutate:V,onSuccess:L,onError:$,onSettled:U}=e;let b;if(a===!0||h==="submit")b=ae(t);else if((0,i.isArray)(a)){const T=ae(t);b={};for(const M of a)b[M]=T[M]}else t.state?.parse?b=t.state.parse():(0,i.isObject)(t.state)&&(b={...t.state});d&&(b=d(b,t,t.state)),(0,i.isFunction)(V)&&V(b,t,t.state);const te=ce?Mt(t,e,b):null;n.__fetching=!0,C(t,{isFetching:!0,isLoading:!1,isStale:!1,isSuccess:!1,error:null,status:"pending",fetchStatus:"fetching"}),F(t,"onFetchStart"),E(e,t,"onFetchStart");const m=r?.analyze?.emitNetwork,W=m?typeof performance<"u"?performance.now():Date.now():0;m&&m({phase:"start",mode:"mutation",from:c,method:u});try{if(D!==!1&&o.auth!==!1&&o.getSession){const j=await o.getSession();if(D===!0&&!j){te!==void 0&&Ue(t,e);const B={message:"Not authenticated"};F(t,"onFetchError",B),E(e,t,"onFetchError",B);return}}const T=o[u];if(!(0,i.isFunction)(T))return;const M={from:c,data:b,headers:Ee,baseUrl:De};P!==void 0&&(M.responseType=P),e.params&&(M.params=Te(e.params,t,r));const z=ne(t,r);z&&(M.headers={...M.headers,"Accept-Language":z});const Y=We(e,!0),J=await Ye(()=>T(M),Y),{data:g,error:k}=J||{};if(k){te!==void 0&&Ue(t,e),C(t,{isFetching:!1,isLoading:!1,isStale:!1,isSuccess:!1,error:k,status:"error",fetchStatus:"idle"}),F(t,"onFetchError",k),(0,i.isFunction)($)&&$(k,b,t),(0,i.isFunction)(U)&&U(null,k,b,t),m&&m({phase:"error",mode:"mutation",from:c,method:u,error:k.message||String(k),durationMs:(typeof performance<"u"?performance.now():Date.now())-W});return}if(delete n.__optimisticSnapshot,C(t,{isFetching:!1,isLoading:!1,isStale:!1,isSuccess:!0,error:null,status:"success",fetchStatus:"idle"}),g!==void 0&&(_||!Ne(g))){const j=_?{[_]:g}:g;t.state?.update&&t.state.update(j,{preventFetch:!0})}F(t,"onFetchComplete",g),E(e,t,"onFetchComplete",g),(0,i.isFunction)(L)&&L(g,b,t),(0,i.isFunction)(U)&&U(g,null,b,t),m&&m({phase:"success",mode:"mutation",ok:!0,from:c,method:u,durationMs:(typeof performance<"u"?performance.now():Date.now())-W}),ue&&tt(ue,c)}catch(T){te!==void 0&&Ue(t,e),C(t,{isFetching:!1,isLoading:!1,isStale:!1,isSuccess:!1,error:T,status:"error",fetchStatus:"idle"}),F(t,"onFetchError",T),E(e,t,"onFetchError",T),(0,i.isFunction)($)&&$(T,b,t),(0,i.isFunction)(U)&&U(null,T,b,t),m&&m({phase:"error",mode:"mutation",from:c,method:u,error:T.message||String(T),durationMs:(typeof performance<"u"?performance.now():Date.now())-W})}finally{n.__fetching=!1}},Rt=e=>{const t=r=>{try{r()}catch{}};for(const r of e.__fetchCleanups||[])t(r);for(const r of e.__fetchListeners||[])t(r);(0,i.isFunction)(e.__unsubscribe)&&t(e.__unsubscribe);for(const r of e.__fetchMounted||[])x.delete(r);e.__fetchCleanups=[],e.__fetchListeners=[],e.__unsubscribe=null,e.__fetchMounted=[]},$e=(e,t,r,s)=>{if(!e||!s?.fetch)return;const n=(0,i.exec)(e,t);if(!n)return;const u=(0,i.isArray)(n)?n.map(a=>He((0,i.exec)(a,t),t)).filter(Boolean):[He(n,t)].filter(Boolean),c=t.__ref;if(c.__fetchMounted)for(const a of c.__fetchMounted)x.delete(a);c.__fetchMounted=[],!c.__fetchDisposer&&(0,i.isArray)(c.__effects)&&(c.__fetchDisposer={dispose:()=>Rt(c)},c.__effects.push(c.__fetchDisposer));for(const a of u){const d=Xe(a.method),_=d?Ot:N,h=!d&&!Re(a)&&a.method!=="subscribe";if(a.on==="create"?_(a,t,s):Promise.resolve().then(()=>{mt({...a,__runner:_},t,s)}),h&&a.on==="create"&&((a.refetchInterval||a.refetchOnWindowFocus!==!1||a.refetchOnReconnect!==!1)&&Ct(a,t,s),!ve(a))){const D={element:t,ref:c,config:a,context:s};x.add(D),c.__fetchMounted.push(D)}}c.refetch=a=>{for(const d of u)N(d,t,s,{force:!0,...a})},c.fetchNextPage=()=>{const a=u[0];if(!a||!a.infinite)return;const d=c.__nextPageParam;if(d==null)return;const _={...a,cursor:d};N(_,t,s,{direction:"next",force:!0})},c.fetchPreviousPage=()=>{const a=u[0];if(!a||!a.infinite)return;const d=c.__prevPageParam;if(d==null)return;const _={...a,cursor:d};N(_,t,s,{direction:"previous",force:!0})}},ie={invalidateQueries:e=>et(Qe(e)),removeQueries:e=>{if(!e){be();return}kt(Qe(e))},getQueryData:e=>re(e)?.data??void 0,setQueryData:(e,t)=>{const r=re(e),s=(0,i.isFunction)(t)?t(r?.data):t;se(e,s,null)},prefetchQuery:async(e,t)=>{const r=t?.fetch;if(!r)return;const s=await qe(r,t);if(!s)return;const o=e.method||"select",n=we(null,t),u=ne(null,t),c=Me({...e,method:o},e.params,n,u),a=s[o];if(!(0,i.isFunction)(a))return;const d={from:e.from,params:e.params,limit:e.limit,offset:e.offset,order:e.order,single:e.single,headers:e.headers,baseUrl:e.baseUrl};u&&(d.headers={...d.headers,"Accept-Language":u}),e.responseType!==void 0&&(d.responseType=e.responseType),o==="rpc"&&(d.read=!Re(e)&&e.read!==!1);const _=++I,h=await a(d);if(h?.data!==void 0&&!h?.error&&!ve(e)&&!Se(c,_)){const D=se(c,h.data,null,_,Le(c,_));D.gcTime=ke(e.cache)?.gcTime||3e5}return h},getCache:()=>v,clear:()=>be(),dropNonLang:e=>{if(!e)return;const t=`:${e}`;for(const[r]of v)r.match(/:([a-z]{2,3})$/i)&&(r.endsWith(t)||be(r))}},rt=(e,t)=>(0,i.isObject)(e)?Ie({method:"select",...e},t,t?.context):e,It={invalidateQueries(e){return ie.invalidateQueries(e)},removeQueries(e){return ie.removeQueries(e)},getQueryData(e){return ie.getQueryData(rt(e,this))},setQueryData(e,t){return ie.setQueryData(rt(e,this),t)}},qt={name:"fetch",create(e){const t=e.fetch;t&&(e.parent||R.clear(),$e(t,e,e.state,e.context))}};var Nt=$e;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
const
|
|
1
|
+
import{openEarly as J,takeEarly as I,earlyKey as W,isScalarParams as Y,withReads as D}from"../early.js";const N=(t,n,s)=>{const d=n&&!n.startsWith("/")?"/":"",a=new URL(`${t}${d}${n}`);if(s)for(const c in s){const r=s[c];r!=null&&a.searchParams.set(c,typeof r=="object"?JSON.stringify(r):r)}return a.toString()},F=({params:t,select:n,limit:s,offset:d,order:a,single:c})=>{const r={...t};return n&&(r.select=n),s&&(r.limit=s),d&&(r.offset=d),c&&(r.single=!0),a&&(typeof a=="string"?r.order=a:Array.isArray(a)?r.order=a.map(b=>`${b.by}:${b.asc===!1?"desc":"asc"}`).join(","):a.by&&(r.order=`${a.by}:${a.asc===!1?"desc":"asc"}`)),r},L=t=>Object.prototype.toString.call(t).slice(8,-1),H=["auto","json","text","blob","arrayBuffer","stream","response"],G={json:async t=>{const n=await t.text();return n?JSON.parse(n):null},text:t=>t.text(),blob:t=>t.blob(),arrayBuffer:t=>t.arrayBuffer(),stream:t=>t.body,response:t=>t},z=t=>{const n=t.headers.get("content-type");return n&&n.includes("json")?t.json():t.text()},M=async t=>{const n=await t.text(),s=t.headers.get("content-type");if(n&&s&&s.includes("json"))try{return JSON.parse(n)}catch{}return n},_=(t,n)=>t?.message||t?.error||n.statusText||`HTTP ${n.status}`,f=async(t,n,s,d)=>{const a=s??"auto";if(!H.includes(a))throw new TypeError(`@symbo.ls/fetch rest: unknown responseType "${a}" \u2014 use one of: ${H.join(", ")}`);const c=d&&await d||await globalThis.fetch(t,n);if(a==="auto"){const r=await z(c);return{data:r,error:c.ok?null:_(r,c),status:c.status}}if(!c.ok){const r=await M(a==="response"?c.clone():c);return{data:a==="response"?c:r,error:_(r,c),status:c.status}}return{data:await G[a](c),error:null,status:c.status}},Q=["FormData","Blob","File","URLSearchParams","ReadableStream","ArrayBuffer"],K=t=>t!==null&&typeof t=="object"&&(ArrayBuffer.isView(t)||Q.includes(L(t))),V=t=>Array.isArray(t)?t:typeof t.entries=="function"?t.entries():Object.entries(t),R=(...t)=>{const n={},s=new Map;for(const d of t)if(d)for(const[a,c]of V(d)){const r=a.toLowerCase();if(s.has(r)&&delete n[s.get(r)],c==null){s.delete(r);continue}s.set(r,a),n[a]=c}return n},v={"Content-Type":"application/json"},X={"Content-Type":void 0},Z=t=>{if(!t||typeof t!="object")return null;const n={};for(const s in t.query||{})n[s.toLowerCase()]=t.query[s];return{params:n,rpc:t.rpc==="get"}},C="content-type",q=(t,n)=>{const s=Object.keys(n);if(!s.length)return t;const d=new URL(t);for(const a of s)d.searchParams.set(a,n[a]);return d.toString()},st=async({url:t,headers:n,auth:s,fetchOptions:d,early:a,reads:c})=>{if(!t)throw new Error("@symbo.ls/fetch rest: url is required");return tt(t,n,s,d,a,c)},tt=(t,n={},s,d={},a,c)=>{let r=s?.token||null;const b=J(D(a,c),n),j=Z(c),B=e=>{if(!j)return null;const o={},l={},i={};for(const u in e){const p=u.toLowerCase();if(p==="authorization")return null;if(p===C)continue;l[u]=e[u];const y=j.params[p];y?i[y]=e[u]:o[u]=e[u]}return{headers:o,adoptHeaders:l,query:i}},x=(e,o)=>{if(!b)return null;let l="";for(const i in o){const u=i.toLowerCase();if(u==="accept-language")l=String(o[i]);else if(b.carried[u]!==o[i])return null}try{return I(W(e(),l),b.maxAge)}catch{return null}},k=()=>r?{Authorization:`Bearer ${r}`}:null,g=e=>R(n,k(),e),T=e=>({...d,...e}),E=(e,o,l)=>{if(!K(o))return T({method:e,headers:R(n,k(),v,l),body:JSON.stringify(o)});const i={method:e,headers:R(n,k(),X,l),body:o};return L(o)==="ReadableStream"&&(i.duplex="half"),T(i)},S=(e,o)=>{const l=o||t;if(e&&(e.startsWith("http://")||e.startsWith("https://")))return e;const i=e&&!e.startsWith("/")?"/":"";return`${l}${i}${e||""}`};return{name:"rest",setToken:e=>{r=e},getSession:async()=>{if(!s?.sessionUrl)return r?{token:r}:null;const e=await f(S(s.sessionUrl,s.baseUrl),T({headers:g()}));return e.error?null:e.data},signIn:async e=>{if(!s?.signInUrl)throw new Error("rest: auth.signInUrl not configured");const o=await f(S(s.signInUrl,s.baseUrl),E("POST",e));return o.data?.token&&(r=o.data.token),o},signOut:async()=>(s?.signOutUrl&&await f(S(s.signOutUrl,s.baseUrl),T({method:"POST",headers:g()})),r=null,{error:null}),select:({from:e,params:o,select:l,limit:i,offset:u,order:p,single:y,headers:h,baseUrl:$,responseType:P})=>{const w=N($||t,e||"",F({params:o,select:l,limit:i,offset:u,order:p,single:y})),O=g(h),U=B(O);if(U){const A=T({headers:U.headers});return f(q(w,U.query),A,P,x(()=>w,U.adoptHeaders))}const m=T({headers:O});return f(w,m,P,x(()=>w,m.headers))},rpc:async({from:e,params:o,headers:l,baseUrl:i,responseType:u,read:p})=>{const y=Y(o),h=()=>N(i||t,`rpc/${e}`,o),$=A=>f(S(`rpc/${e}`,i),E("POST",o,l),u,A),P=g(l),w=p===!0&&j&&j.rpc&&y?B(P):null;let O=null;if(w)try{O=h()}catch{O=null}if(!O)return $(b&&b.rpc&&y?x(h,P):null);const U=T({method:"GET",headers:w.headers}),m=await f(q(O,w.query),U,u,x(()=>O,w.adoptHeaders));return m.status===405?$(null):m},insert:({from:e,data:o,headers:l,baseUrl:i,responseType:u})=>f(S(e,i),E("POST",o,l),u),update:({from:e,data:o,params:l,method:i,headers:u,baseUrl:p,responseType:y})=>{const h=l?.id||o?.id,$=h?`${e}/${h}`:e;return f(S($,p),E(i||"PATCH",o,u),y)},upsert:({from:e,data:o,params:l,method:i,headers:u,baseUrl:p,responseType:y})=>{const h=l?.id||o?.id,$=h?`${e}/${h}`:e;return f(S($,p),E(i||"PUT",o,u),y)},delete:({from:e,params:o,headers:l,baseUrl:i,responseType:u})=>{const p=o?.id,y=p?`${e}/${p}`:e;return f(S(y,i),T({method:"DELETE",headers:g(l)}),u)}}};export{N as buildUrl,tt as restAdapter,F as selectQuery,st as setup};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const d="@symbo.ls/fetch:EARLY",g=3e4,h=(e,n)=>{const t=new URL(e);return t.searchParams.sort(),t.toString()+" "+(n||"")},A=e=>{if(e==null)return!0;if(typeof e!="object"||Array.isArray(e))return!1;const n=Object.getPrototypeOf(e);if(n!==Object.prototype&&n!==null)return!1;for(const t in e){const r=e[t];if(!(r===void 0||typeof r=="string"||typeof r=="boolean")&&!(typeof r=="number"&&isFinite(r)))return!1}return!0},x=(e,n)=>{const t=i=>String(i).split("/").filter(Boolean),r=t(n);let o=null;for(let i=0;i<e.length;i++){const s=t(e[i]),l=s[s.length-1]==="*",f=l?s.length-1:s.length;if(l?r.length<f:r.length!==f)continue;const p={};let u=l?-1:0,a=!0;for(let c=0;c<f;c++)if(s[c].charAt(0)===":"){try{p[s[c].slice(1)]=decodeURIComponent(r[c])}catch{a=!1;break}u+=1}else if(s[c]===r[c])u+=3;else{a=!1;break}a&&(!o||u>o.score)&&(o={index:i,params:p,score:u})}return o&&{index:o.index,params:o.params}},y=()=>Symbol.for(d),m=(e,n)=>{if(!e||typeof e!="object"||!n||typeof n!="object")return e;const t={...e};return t.query===void 0&&n.query!==void 0&&(t.query=n.query),t.rpc===void 0&&n.rpc!==void 0&&(t.rpc=n.rpc),t},E=(e,n)=>{if(!e||typeof e!="object")return null;const t=y();let r=globalThis[t];r||(r={time:Date.now(),entries:{}},globalThis[t]=r),r.closed=!0;const o={};for(const s in e.query||{})for(const l in n||{})l.toLowerCase()===s.toLowerCase()&&(o[l.toLowerCase()]=n[l]);const i=typeof e.maxAge=="number"&&e.maxAge>=0?e.maxAge:3e4;return{carried:o,rpc:e.rpc==="get",maxAge:i}},w=(e,n=3e4)=>{const t=globalThis[y()],r=t&&t.entries&&t.entries[e];return!r||(delete t.entries[e],!(Date.now()-r.time<=n))?null:Promise.resolve(r.answer).then(o=>o&&o.ok&&!o.bodyUsed?o:null,()=>null)},L=()=>{const e=globalThis[y()];e&&e.entries&&(e.entries={})};export{d as EARLY_KEY,g as EARLY_MAX_AGE,L as dropEarly,h as earlyKey,A as isScalarParams,x as matchEarlyRoute,E as openEarly,w as takeEarly,m as withReads};
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import{buildUrl as l,selectQuery as f}from"./adapters/rest.js";import{EARLY_KEY as g,earlyKey as y,isScalarParams as h,matchEarlyRoute as m,withReads as p}from"./early.js";const d="smbls_lang",v=["credentials","mode","cache","redirect","referrerPolicy","priority"],c=r=>{try{return new Function(r),!0}catch{return!1}},b=(r,t)=>{const e=typeof r=="function"?r.toString():String(r).trim();if(c("return ("+e+")"))return"("+e+")";if(c("return ({"+e+"})"))return"Object.values({"+e+"})[0]";throw new Error(`@symbo.ls/fetch early: the request function of ${t} does not compile on its own`)},i=(r,t)=>typeof r=="function"||typeof r=="string"?b(r,t):JSON.stringify(Array.isArray(r)?r:[]),q=r=>{const t=r.state&&typeof r.state.lang=="string"?r.state.lang:"",e=r.polyglot;return e&&typeof e=="object"?{storage:e.storageLangKey||d,fallback:t||e.defaultLang||"en"}:{storage:"",fallback:t}},S=(r,t)=>{const e={};for(const a in r||{}){const o=Object.keys(t||{}).find(s=>s.toLowerCase()===a.toLowerCase());if(!o)throw new Error(`@symbo.ls/fetch early.query: "${a}" is not one of the adapter's configured headers`);e[r[a]]=t[o]}return e},w=r=>{const t={};for(const e of v)r&&r[e]!==void 0&&(t[e]=r[e]);return t.cache===void 0&&(t.cache="no-store"),t},O=(r={})=>{const t=r&&r.fetch,e=t&&p(t.early,t.reads);if(!e||typeof e!="object"||t.adapter!=="rest"||!t.url)return"";const a=e.routes&&typeof e.routes=="object"?Object.keys(e.routes):[];if(!a.length&&!e.always)return"";const o={url:t.url,query:S(e.query,t.headers),rpc:e.rpc==="get",fetchOptions:w(t.fetchOptions),lang:q(r)},s=a.map(n=>`[${JSON.stringify(n)}, ${i(e.routes[n],JSON.stringify(n))}]`).join(`,
|
|
2
|
+
`),u=e.always?i(e.always,"`always`"):"[]";return`/* @symbo.ls/fetch \u2014 fetch.early: the first view's requests, sent before the app boots */
|
|
3
|
+
;(function () {
|
|
4
|
+
var g = globalThis
|
|
5
|
+
var K = Symbol.for(${JSON.stringify(g)})
|
|
6
|
+
if (g[K] || typeof g.fetch !== 'function' || !g.location) return
|
|
7
|
+
var registry = g[K] = { time: Date.now(), entries: {} }
|
|
8
|
+
var config = ${JSON.stringify(o)}
|
|
9
|
+
var buildUrl = ${l.toString()}
|
|
10
|
+
var selectQuery = ${f.toString()}
|
|
11
|
+
var earlyKey = ${y.toString()}
|
|
12
|
+
var isScalarParams = ${h.toString()}
|
|
13
|
+
var matchEarlyRoute = ${m.toString()}
|
|
14
|
+
var always = ${u}
|
|
15
|
+
var routes = [
|
|
16
|
+
${s}
|
|
17
|
+
]
|
|
18
|
+
var storage = function (key) {
|
|
19
|
+
try { return key ? g.localStorage.getItem(key) : null } catch (e) { return null }
|
|
20
|
+
}
|
|
21
|
+
var lang = (config.lang.storage && storage(config.lang.storage)) || config.lang.fallback || ''
|
|
22
|
+
var ctx = { path: g.location.pathname, query: new URLSearchParams(g.location.search), lang: lang, storage: storage }
|
|
23
|
+
var list = function (requests, params) {
|
|
24
|
+
try {
|
|
25
|
+
var out = typeof requests === 'function' ? requests(params, ctx) : requests
|
|
26
|
+
return Array.isArray(out) ? out : []
|
|
27
|
+
} catch (e) {
|
|
28
|
+
return []
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
var match = matchEarlyRoute(routes.map(function (route) { return route[0] }), ctx.path)
|
|
32
|
+
var requests = list(always, {}).concat(match ? list(routes[match.index][1], match.params) : [])
|
|
33
|
+
for (var i = 0; i < requests.length; i++) {
|
|
34
|
+
try {
|
|
35
|
+
var request = requests[i]
|
|
36
|
+
if (!request || typeof request !== 'object' || !request.from) continue
|
|
37
|
+
var method = request.method || 'select'
|
|
38
|
+
var url
|
|
39
|
+
if (method === 'select') url = buildUrl(config.url, request.from, selectQuery(request))
|
|
40
|
+
else if (method === 'rpc' && config.rpc && isScalarParams(request.params)) url = buildUrl(config.url, 'rpc/' + request.from, request.params)
|
|
41
|
+
else continue
|
|
42
|
+
var language = request.lang === false ? '' : lang
|
|
43
|
+
var key = earlyKey(url, language)
|
|
44
|
+
if (registry.entries[key]) continue
|
|
45
|
+
var address = new URL(url)
|
|
46
|
+
for (var name in config.query) address.searchParams.set(name, config.query[name])
|
|
47
|
+
var options = Object.assign({}, config.fetchOptions, { method: 'GET' })
|
|
48
|
+
if (language) options.headers = { 'Accept-Language': language }
|
|
49
|
+
registry.entries[key] = { time: Date.now(), answer: g.fetch(address.toString(), options).catch(function () { return null }) }
|
|
50
|
+
} catch (e) {}
|
|
51
|
+
}
|
|
52
|
+
})()
|
|
53
|
+
`.replace(/<\/script/gi,"<\\/script")};var L=O;export{O as createEarlyScript,L as default};
|