grist-widget-sdk 0.3.27 → 0.5.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.
Files changed (88) hide show
  1. package/CHANGELOG.md +84 -0
  2. package/README.md +79 -208
  3. package/dist/app.cjs +1336 -4415
  4. package/dist/app.cjs.map +1 -1
  5. package/dist/app.d.cts +6 -103
  6. package/dist/app.d.ts +6 -103
  7. package/dist/app.js +5 -7
  8. package/dist/chunk-4ZGVKGDF.js +204 -0
  9. package/dist/chunk-4ZGVKGDF.js.map +1 -0
  10. package/dist/{chunk-6Y2IONGJ.js → chunk-LSALXIGM.js} +191 -20
  11. package/dist/chunk-LSALXIGM.js.map +1 -0
  12. package/dist/chunk-MAPAWVQC.js +1898 -0
  13. package/dist/chunk-MAPAWVQC.js.map +1 -0
  14. package/dist/{chunk-YQNMIL33.js → chunk-OXA2VITC.js} +532 -181
  15. package/dist/chunk-OXA2VITC.js.map +1 -0
  16. package/dist/define-widget-B1FIvI-h.d.cts +433 -0
  17. package/dist/define-widget-B9gEtJP0.d.ts +433 -0
  18. package/dist/emulator/testing.cjs +3341 -6512
  19. package/dist/emulator/testing.cjs.map +1 -1
  20. package/dist/emulator/testing.d.cts +29 -14
  21. package/dist/emulator/testing.d.ts +29 -14
  22. package/dist/emulator/testing.js +78 -72
  23. package/dist/emulator/testing.js.map +1 -1
  24. package/dist/emulator.cjs +63 -249
  25. package/dist/emulator.cjs.map +1 -1
  26. package/dist/emulator.d.cts +6 -8
  27. package/dist/emulator.d.ts +6 -8
  28. package/dist/emulator.js +5 -11
  29. package/dist/index.cjs +1442 -4862
  30. package/dist/index.cjs.map +1 -1
  31. package/dist/index.d.cts +81 -260
  32. package/dist/index.d.ts +81 -260
  33. package/dist/index.js +12 -158
  34. package/dist/mount-grist-widget-CkB-3iG_.d.ts +137 -0
  35. package/dist/mount-grist-widget-Dtelqao_.d.cts +137 -0
  36. package/dist/{inline-DpcT8tV9.d.ts → templates-CGmRIQBV.d.cts} +89 -35
  37. package/dist/{inline-C7DkvuET.d.cts → templates-Cq94qOcf.d.ts} +89 -35
  38. package/dist/{types-D3JxUCfL.d.cts → types-DBStn0Dk.d.cts} +2 -26
  39. package/dist/{types-D3JxUCfL.d.ts → types-DBStn0Dk.d.ts} +2 -26
  40. package/package.json +8 -37
  41. package/dist/advanced.cjs +0 -2799
  42. package/dist/advanced.cjs.map +0 -1
  43. package/dist/advanced.d.cts +0 -822
  44. package/dist/advanced.d.ts +0 -822
  45. package/dist/advanced.js +0 -872
  46. package/dist/advanced.js.map +0 -1
  47. package/dist/chunk-22U7WAY3.js +0 -463
  48. package/dist/chunk-22U7WAY3.js.map +0 -1
  49. package/dist/chunk-64SVRWW7.js +0 -758
  50. package/dist/chunk-64SVRWW7.js.map +0 -1
  51. package/dist/chunk-6Y2IONGJ.js.map +0 -1
  52. package/dist/chunk-B4AKVSWV.js +0 -2362
  53. package/dist/chunk-B4AKVSWV.js.map +0 -1
  54. package/dist/chunk-ELGVOHFD.js +0 -32
  55. package/dist/chunk-ELGVOHFD.js.map +0 -1
  56. package/dist/chunk-GTTD5HPO.js +0 -36
  57. package/dist/chunk-GTTD5HPO.js.map +0 -1
  58. package/dist/chunk-NO6FYX33.js +0 -2084
  59. package/dist/chunk-NO6FYX33.js.map +0 -1
  60. package/dist/chunk-OPTOYD2Y.js +0 -277
  61. package/dist/chunk-OPTOYD2Y.js.map +0 -1
  62. package/dist/chunk-PM3B4WYV.js +0 -12
  63. package/dist/chunk-PM3B4WYV.js.map +0 -1
  64. package/dist/chunk-REV5AUXD.js +0 -25
  65. package/dist/chunk-REV5AUXD.js.map +0 -1
  66. package/dist/chunk-YQNMIL33.js.map +0 -1
  67. package/dist/create-grist-emulator-BCqp1BF9.d.ts +0 -81
  68. package/dist/create-grist-emulator-DBM8OSIR.d.cts +0 -81
  69. package/dist/emulator/devtools.cjs +0 -1404
  70. package/dist/emulator/devtools.cjs.map +0 -1
  71. package/dist/emulator/devtools.d.cts +0 -48
  72. package/dist/emulator/devtools.d.ts +0 -48
  73. package/dist/emulator/devtools.js +0 -506
  74. package/dist/emulator/devtools.js.map +0 -1
  75. package/dist/emulator/transports.cjs +0 -1132
  76. package/dist/emulator/transports.cjs.map +0 -1
  77. package/dist/emulator/transports.d.cts +0 -38
  78. package/dist/emulator/transports.d.ts +0 -38
  79. package/dist/emulator/transports.js +0 -12
  80. package/dist/emulator/transports.js.map +0 -1
  81. package/dist/templates-8k2LKoO-.d.cts +0 -24
  82. package/dist/templates-DIwi_mvI.d.ts +0 -24
  83. package/dist/use-grist-reads-DUMvJgV7.d.ts +0 -480
  84. package/dist/use-grist-reads-DpjVuI0H.d.cts +0 -480
  85. package/dist/use-grist-types-DdOLEJXN.d.cts +0 -499
  86. package/dist/use-grist-types-kwxoFeub.d.ts +0 -499
  87. package/dist/use-grist-widget-options-from-context-CGOlQ5Vc.d.cts +0 -43
  88. package/dist/use-grist-widget-options-from-context-CGOlQ5Vc.d.ts +0 -43
@@ -1,2084 +0,0 @@
1
- import {
2
- ACCESS_RANK,
3
- formatInsufficientAccessMessage,
4
- isAccessSufficient,
5
- parseGristRequiredAccess
6
- } from "./chunk-OPTOYD2Y.js";
7
-
8
- // src/sdk/helpers/grist-fetch-with-auth.ts
9
- var TOKEN_TTL_MS = 45e3;
10
- var cache = /* @__PURE__ */ new Map();
11
- var inFlight = /* @__PURE__ */ new Map();
12
- function cacheKey(readOnly) {
13
- return readOnly ? "ro" : "rw";
14
- }
15
- async function getGristAccessToken(docApi, options) {
16
- if (!docApi.getAccessToken) {
17
- throw new Error("getAccessToken is not available on docApi (need higher access level)");
18
- }
19
- const readOnly = options?.readOnly ?? false;
20
- const key = cacheKey(readOnly);
21
- const now = Date.now();
22
- const hit = cache.get(key);
23
- if (hit && now - hit.fetchedAt < TOKEN_TTL_MS) {
24
- return hit.token;
25
- }
26
- const pending = inFlight.get(key);
27
- if (pending) return pending;
28
- const next = docApi.getAccessToken({ readOnly }).then((token) => {
29
- cache.set(key, { token, fetchedAt: Date.now() });
30
- inFlight.delete(key);
31
- return token;
32
- });
33
- inFlight.set(key, next);
34
- return next;
35
- }
36
- function clearGristAccessTokenCache() {
37
- cache.clear();
38
- inFlight.clear();
39
- }
40
- async function fetchWithGristAuth(docApi, path, init) {
41
- const readOnly = init?.readOnly ?? false;
42
- let token;
43
- try {
44
- token = await getGristAccessToken(docApi, { readOnly });
45
- } catch (err) {
46
- clearGristAccessTokenCache();
47
- throw err;
48
- }
49
- const isAbsolute = /^https?:\/\//i.test(path);
50
- const cleanPath = isAbsolute ? path : path.startsWith("/") ? path : `/${path}`;
51
- const url = isAbsolute ? new URL(path) : new URL(`${token.baseUrl.replace(/\/$/, "")}${cleanPath}`);
52
- if (!url.searchParams.has("auth")) url.searchParams.set("auth", token.token);
53
- const headers = new Headers(init?.headers ?? {});
54
- headers.delete("Authorization");
55
- const response = await fetch(url.toString(), { ...init, headers });
56
- if (response.status === 401) {
57
- clearGristAccessTokenCache();
58
- const retryToken = await getGristAccessToken(docApi, { readOnly });
59
- url.searchParams.set("auth", retryToken.token);
60
- return fetch(url.toString(), { ...init, headers });
61
- }
62
- return response;
63
- }
64
-
65
- // src/sdk/helpers/grist-mappings.ts
66
- function asColumnSpec(entry) {
67
- return typeof entry === "string" ? { name: entry } : entry;
68
- }
69
- function validateColumnMappings(spec, mappings) {
70
- const missing = [];
71
- const emptyMultiples = [];
72
- if (!spec) return { ok: true, pending: false, missing, emptyMultiples };
73
- const m = mappings ?? {};
74
- for (const raw of spec) {
75
- const col = asColumnSpec(raw);
76
- if (col.optional) continue;
77
- const value = m[col.name];
78
- if (col.allowMultiple) {
79
- if (value === void 0) {
80
- missing.push(col.name);
81
- } else if (!Array.isArray(value) || value.length === 0) {
82
- emptyMultiples.push(col.name);
83
- }
84
- } else {
85
- if (value === void 0 || value === null || value === "") missing.push(col.name);
86
- }
87
- }
88
- return {
89
- ok: missing.length === 0 && emptyMultiples.length === 0,
90
- pending: false,
91
- missing,
92
- emptyMultiples
93
- };
94
- }
95
- var pendingColumnMappingStatus = {
96
- ok: true,
97
- pending: true,
98
- missing: [],
99
- emptyMultiples: []
100
- };
101
-
102
- // src/sdk/internal/hooks/use-grist-core.ts
103
- import { useCallback, useMemo, useSyncExternalStore } from "react";
104
-
105
- // src/sdk/internal/handshake/types.ts
106
- var ZERO_GENERATION = 0;
107
- function nextGeneration(current) {
108
- return current + 1;
109
- }
110
- var MAPPING_SOURCE_PRIORITY = [
111
- "section_api",
112
- "stream_record",
113
- "stream_records",
114
- "stream_new_record"
115
- ];
116
- function initialGristSnapshot() {
117
- return {
118
- generation: ZERO_GENERATION,
119
- lifecycle: { phase: "idle" },
120
- link: { state: "connected", lastSuccessMs: null, missedPings: 0 },
121
- authz: { state: "pending", declared: "read table" },
122
- config: { mappings: { state: "not_declared" } },
123
- sync: {
124
- record: { state: "cold" },
125
- records: { state: "cold" },
126
- options: { state: "cold" },
127
- newRecord: { state: "cold" },
128
- currentTable: { state: "unknown" }
129
- }
130
- };
131
- }
132
-
133
- // src/sdk/internal/handshake/actions.ts
134
- function hasGenerationStamp(action) {
135
- return "generation" in action && typeof action.generation === "number";
136
- }
137
-
138
- // src/sdk/internal/handshake/mapping-resolver.ts
139
- var MappingResolver = class {
140
- constructor(declared, generation) {
141
- /** Latest accepted payload per source. */
142
- this.payloads = /* @__PURE__ */ new Map();
143
- /** Last resolved state, used to detect duplicate ingests. */
144
- this.lastResolvedHash = null;
145
- this.declared = declared;
146
- this.currentGeneration = generation;
147
- }
148
- /**
149
- * Replace the declared columns (e.g. user passed a new `columns` array to
150
- * the provider). Clears accumulated payloads — they were validated against
151
- * the previous declaration.
152
- */
153
- redeclare(declared, atGeneration) {
154
- this.declared = declared;
155
- this.currentGeneration = atGeneration;
156
- this.payloads.clear();
157
- this.lastResolvedHash = null;
158
- }
159
- /** Bump the active generation. Payloads from older generations are dropped. */
160
- bumpGeneration(next) {
161
- if (next <= this.currentGeneration) return;
162
- this.currentGeneration = next;
163
- for (const [src, p] of this.payloads) {
164
- if (p.generation < next) this.payloads.delete(src);
165
- }
166
- this.lastResolvedHash = null;
167
- }
168
- /** Forget every payload and reset the hash. The declaration is preserved. */
169
- reset() {
170
- this.payloads.clear();
171
- this.lastResolvedHash = null;
172
- }
173
- /** Cheap, deterministic snapshot for tests/debug. */
174
- knownSources() {
175
- return [...this.payloads.keys()];
176
- }
177
- /**
178
- * Ingest one payload. Returns a {@link ResolveOutcome}:
179
- * - `still_pending` — no payloads accepted yet.
180
- * - `no_change/stale_*` — input generation is older than current.
181
- * - `no_change/duplicate_payload` — input did not move the resolution.
182
- * - `resolved` — new resolution differs from the previous one.
183
- *
184
- * Call {@link current} to read the latest resolution without affecting
185
- * the duplicate-detection hash.
186
- */
187
- ingest(input) {
188
- if (input.generation < this.currentGeneration) {
189
- return { kind: "no_change", reason: "stale_generation" };
190
- }
191
- if (input.generation > this.currentGeneration) {
192
- this.bumpGeneration(input.generation);
193
- }
194
- this.payloads.set(input.source, input);
195
- const computed = this.compute();
196
- if (computed === null) return { kind: "still_pending" };
197
- const hash = computeMappingHash(
198
- computed.mappings,
199
- computed.state === "complete",
200
- computed.source
201
- );
202
- if (hash === this.lastResolvedHash) {
203
- return { kind: "no_change", reason: "duplicate_payload" };
204
- }
205
- this.lastResolvedHash = hash;
206
- return { kind: "resolved", state: computed };
207
- }
208
- /**
209
- * Return the resolver's current resolution (pure read). Equivalent to
210
- * `ingest(...)` without mutating any state — used by tests and by the
211
- * reducer when re-applying after `MAPPING_INVALIDATION_RESOLVE`.
212
- */
213
- current() {
214
- const computed = this.compute();
215
- if (computed === null) return { kind: "still_pending" };
216
- return { kind: "resolved", state: computed };
217
- }
218
- /**
219
- * Compute the current best mapping from accumulated payloads (pure).
220
- *
221
- * Priority: higher-priority sources **override** specific keys from
222
- * lower-priority sources. Keys absent from a higher-priority source fall
223
- * back to lower-priority sources. This matches the production behaviour
224
- * where `sectionApi.mappings()` is authoritative for the keys it reports,
225
- * but stream payloads can fill in keys the section_api hasn't reported yet.
226
- */
227
- compute() {
228
- if (this.payloads.size === 0) return null;
229
- const merged = {};
230
- let latestReportedAt = 0;
231
- const contributors = [];
232
- for (const src of [...MAPPING_SOURCE_PRIORITY].reverse()) {
233
- const p = this.payloads.get(src);
234
- if (!p) continue;
235
- contributors.push(src);
236
- if (p.receivedAtMs > latestReportedAt) latestReportedAt = p.receivedAtMs;
237
- if (p.payload === null) continue;
238
- for (const [k, v] of Object.entries(p.payload)) {
239
- merged[k] = v;
240
- }
241
- }
242
- if (contributors.length === 0) return null;
243
- const validation = validateColumnMappings(this.declared, merged);
244
- const source = contributors.length === 1 ? contributors[0] : "merged";
245
- if (validation.ok) {
246
- return {
247
- state: "complete",
248
- declared: this.declared,
249
- mappings: merged,
250
- source,
251
- reportedAtMs: latestReportedAt
252
- };
253
- }
254
- return {
255
- state: "incomplete",
256
- declared: this.declared,
257
- mappings: merged,
258
- missing: validation.missing,
259
- emptyMultiples: validation.emptyMultiples,
260
- source,
261
- reportedAtMs: latestReportedAt
262
- };
263
- }
264
- };
265
- function computeMappingHash(mappings, ok, source) {
266
- const keys = Object.keys(mappings).sort();
267
- const body = keys.map((k) => {
268
- const v = mappings[k];
269
- if (Array.isArray(v)) return `${k}=[${v.join(",")}]`;
270
- return `${k}=${v ?? ""}`;
271
- }).join("|");
272
- return `${ok ? "OK" : "KO"}::${source}::${body}`;
273
- }
274
-
275
- // src/sdk/internal/handshake/reducer.ts
276
- function createReducerContext() {
277
- return { resolver: null };
278
- }
279
- var DEFAULT_REDUCER_CONFIG = {
280
- staleAfterMissed: 1,
281
- lostAfterMissed: 3
282
- };
283
- function gristReducer(snapshot, action, ctx, config = DEFAULT_REDUCER_CONFIG) {
284
- if (hasGenerationStamp(action) && action.generation < snapshot.generation) {
285
- return snapshot;
286
- }
287
- switch (action.type) {
288
- // -- Lifecycle --------------------------------------------------------
289
- case "DETECT_START":
290
- return reduceDetectStart(snapshot, action.atMs);
291
- case "DETECT_TICK":
292
- return reduceDetectTick(snapshot, action.attempts);
293
- case "DETECT_AVAILABLE":
294
- return reduceDetectAvailable(snapshot, action.atMs);
295
- case "DETECT_TIMEOUT":
296
- return reduceTerminate(snapshot, {
297
- kind: "script_timeout",
298
- attempts: action.attempts
299
- }, action.atMs);
300
- case "NOT_EMBEDDED":
301
- return reduceTerminate(snapshot, { kind: "not_embedded" }, action.atMs);
302
- case "NEGOTIATE_START":
303
- return reduceNegotiateStart(snapshot, action.access, action.atMs);
304
- case "NEGOTIATE_SUCCESS":
305
- return reduceNegotiateSuccess(snapshot, action.access, action.grantedLevel, action.atMs);
306
- case "NEGOTIATE_FAIL":
307
- return reduceTerminate(snapshot, action.reason, action.atMs);
308
- case "TERMINATE":
309
- return reduceTerminate(snapshot, action.reason, action.atMs);
310
- case "AUTHZ_REPORT":
311
- return reduceAuthzReport(snapshot, action.level, action.atMs);
312
- // -- Link -------------------------------------------------------------
313
- case "RPC_SUCCESS":
314
- case "HEARTBEAT_OK":
315
- return reduceLinkSuccess(snapshot, action.atMs);
316
- case "RPC_FAILURE":
317
- case "HEARTBEAT_FAIL":
318
- return reduceLinkFailure(snapshot, action.atMs, config);
319
- // -- Generation -------------------------------------------------------
320
- case "BUMP_GENERATION":
321
- return reduceBumpGeneration(snapshot, ctx);
322
- // -- Config / mappings -----------------------------------------------
323
- case "MAPPING_DECLARE":
324
- case "MAPPING_REPORT":
325
- case "MAPPING_INVALIDATE":
326
- case "MAPPING_INVALIDATION_RESOLVE":
327
- case "MAPPING_TIMEOUT":
328
- return reduceMapping(snapshot, action, ctx);
329
- // -- Sync -------------------------------------------------------------
330
- case "STREAM_RECEIVED":
331
- case "STREAM_WARMING":
332
- case "STREAM_STALE":
333
- return reduceStream(snapshot, action);
334
- case "CURRENT_TABLE_KNOWN":
335
- return updateSync(snapshot, {
336
- ...snapshot.sync,
337
- currentTable: { state: "known", tableId: action.tableId, refreshing: false }
338
- });
339
- case "CURRENT_TABLE_REFRESH_START":
340
- if (snapshot.sync.currentTable.state !== "known") return snapshot;
341
- return updateSync(snapshot, {
342
- ...snapshot.sync,
343
- currentTable: { ...snapshot.sync.currentTable, refreshing: true }
344
- });
345
- case "CURRENT_TABLE_ERROR":
346
- return updateSync(snapshot, {
347
- ...snapshot.sync,
348
- currentTable: { state: "errored", message: action.message, sinceMs: action.atMs }
349
- });
350
- default: {
351
- const _exhaustive = action;
352
- void _exhaustive;
353
- return snapshot;
354
- }
355
- }
356
- }
357
- function reduceDetectStart(snapshot, atMs) {
358
- if (snapshot.lifecycle.phase !== "idle") return snapshot;
359
- return {
360
- ...snapshot,
361
- lifecycle: { phase: "detecting", attempts: 0, startedAtMs: atMs }
362
- };
363
- }
364
- function reduceDetectTick(snapshot, attempts) {
365
- if (snapshot.lifecycle.phase !== "detecting") return snapshot;
366
- if (attempts === snapshot.lifecycle.attempts) return snapshot;
367
- return {
368
- ...snapshot,
369
- lifecycle: { ...snapshot.lifecycle, attempts }
370
- };
371
- }
372
- function reduceDetectAvailable(snapshot, atMs) {
373
- if (snapshot.lifecycle.phase !== "detecting" && snapshot.lifecycle.phase !== "idle") {
374
- return snapshot;
375
- }
376
- return {
377
- ...snapshot,
378
- lifecycle: {
379
- phase: "negotiating",
380
- access: snapshot.authz.declared,
381
- startedAtMs: atMs
382
- }
383
- };
384
- }
385
- function reduceNegotiateStart(snapshot, access, atMs) {
386
- if (snapshot.lifecycle.phase === "terminated") return snapshot;
387
- return {
388
- ...snapshot,
389
- authz: { state: "pending", declared: access },
390
- lifecycle: snapshot.lifecycle.phase === "online" ? snapshot.lifecycle : { phase: "negotiating", access, startedAtMs: atMs }
391
- };
392
- }
393
- function authzDeclared(snapshot) {
394
- return snapshot.authz.declared;
395
- }
396
- function reduceAuthzReport(snapshot, level, _atMs) {
397
- if (snapshot.lifecycle.phase !== "online") return snapshot;
398
- const declared = authzDeclared(snapshot);
399
- if (isAccessSufficient(level, declared)) {
400
- const previousLevel = snapshot.authz.state === "granted" ? snapshot.authz.level : null;
401
- const widened = previousLevel !== null && ACCESS_RANK[level] > ACCESS_RANK[previousLevel];
402
- const nextAuthz2 = {
403
- state: "granted",
404
- level,
405
- declared,
406
- widened
407
- };
408
- if (snapshot.authz.state === "granted" && snapshot.authz.level === nextAuthz2.level && snapshot.authz.declared === nextAuthz2.declared && snapshot.authz.widened === nextAuthz2.widened) {
409
- return snapshot;
410
- }
411
- return { ...snapshot, authz: nextAuthz2 };
412
- }
413
- const message = formatInsufficientAccessMessage(declared, level);
414
- const nextAuthz = { state: "denied", declared, message };
415
- if (snapshot.authz.state === "denied" && snapshot.authz.declared === nextAuthz.declared && snapshot.authz.message === nextAuthz.message) {
416
- return snapshot;
417
- }
418
- return { ...snapshot, authz: nextAuthz };
419
- }
420
- function reduceNegotiateSuccess(snapshot, access, grantedLevel, atMs) {
421
- if (snapshot.lifecycle.phase === "terminated") return snapshot;
422
- const previousLevel = snapshot.authz.state === "granted" ? snapshot.authz.level : null;
423
- const widened = previousLevel !== null && ACCESS_RANK[grantedLevel] > ACCESS_RANK[previousLevel];
424
- return {
425
- ...snapshot,
426
- authz: {
427
- state: "granted",
428
- level: grantedLevel,
429
- declared: access,
430
- widened
431
- },
432
- lifecycle: snapshot.lifecycle.phase === "online" ? snapshot.lifecycle : { phase: "online", sinceMs: atMs, declaredAccess: access },
433
- link: { state: "connected", lastSuccessMs: atMs, missedPings: 0 }
434
- };
435
- }
436
- function reduceTerminate(snapshot, reason, atMs) {
437
- if (snapshot.lifecycle.phase === "terminated") return snapshot;
438
- const lifecycle = { phase: "terminated", reason, atMs };
439
- return { ...snapshot, lifecycle };
440
- }
441
- function reduceLinkSuccess(snapshot, atMs) {
442
- if (snapshot.lifecycle.phase !== "online") return snapshot;
443
- const link = { state: "connected", lastSuccessMs: atMs, missedPings: 0 };
444
- if (snapshot.link.state === link.state && snapshot.link.lastSuccessMs === link.lastSuccessMs && snapshot.link.missedPings === link.missedPings) {
445
- return snapshot;
446
- }
447
- return { ...snapshot, link };
448
- }
449
- function reduceLinkFailure(snapshot, _atMs, config) {
450
- if (snapshot.lifecycle.phase !== "online") return snapshot;
451
- const missed = snapshot.link.missedPings + 1;
452
- let state = snapshot.link.state;
453
- if (missed >= config.lostAfterMissed) state = "lost";
454
- else if (missed >= config.staleAfterMissed) state = "stale";
455
- return {
456
- ...snapshot,
457
- link: { state, lastSuccessMs: snapshot.link.lastSuccessMs, missedPings: missed }
458
- };
459
- }
460
- function reduceBumpGeneration(snapshot, ctx) {
461
- const next = nextGeneration(snapshot.generation);
462
- ctx.resolver?.bumpGeneration(next);
463
- return {
464
- ...snapshot,
465
- generation: next,
466
- // Marking streams as warming again ensures hooks treat the data as
467
- // "in transit" until a fresh event arrives under the new generation.
468
- sync: {
469
- ...snapshot.sync,
470
- record: degradeForRefresh(snapshot.sync.record, snapshot.generation),
471
- records: degradeForRefresh(snapshot.sync.records, snapshot.generation),
472
- options: degradeForRefresh(snapshot.sync.options, snapshot.generation),
473
- newRecord: degradeForRefresh(snapshot.sync.newRecord, snapshot.generation)
474
- }
475
- };
476
- }
477
- function degradeForRefresh(freshness, prevGeneration) {
478
- if (freshness.state === "hot" && freshness.generation === prevGeneration) {
479
- return { state: "stale", lastEventMs: freshness.lastEventMs, reason: "host_quiet" };
480
- }
481
- return freshness;
482
- }
483
- function reduceMapping(snapshot, action, ctx) {
484
- switch (action.type) {
485
- case "MAPPING_DECLARE": {
486
- if (action.declared.length === 0) {
487
- if (snapshot.config.mappings.state === "not_declared") return snapshot;
488
- ctx.resolver = null;
489
- return {
490
- ...snapshot,
491
- config: { mappings: { state: "not_declared" } }
492
- };
493
- }
494
- if (!ctx.resolver) {
495
- ctx.resolver = new MappingResolver(action.declared, snapshot.generation);
496
- } else {
497
- ctx.resolver.redeclare(action.declared, snapshot.generation);
498
- }
499
- return {
500
- ...snapshot,
501
- config: {
502
- mappings: {
503
- state: "pending",
504
- declared: action.declared,
505
- declaredAtMs: action.atMs
506
- }
507
- }
508
- };
509
- }
510
- case "MAPPING_REPORT": {
511
- if (!ctx.resolver) return snapshot;
512
- const outcome = ctx.resolver.ingest({
513
- source: action.source,
514
- payload: action.payload,
515
- receivedAtMs: action.atMs,
516
- generation: action.generation
517
- });
518
- if (outcome.kind !== "resolved") return snapshot;
519
- return applyResolved(snapshot, outcome.state);
520
- }
521
- case "MAPPING_INVALIDATE": {
522
- const previous = snapshot.config.mappings;
523
- if (previous.state !== "complete" && previous.state !== "incomplete") {
524
- return snapshot;
525
- }
526
- return {
527
- ...snapshot,
528
- config: {
529
- mappings: {
530
- state: "invalidating",
531
- previous,
532
- sinceMs: action.atMs
533
- }
534
- }
535
- };
536
- }
537
- case "MAPPING_INVALIDATION_RESOLVE": {
538
- if (snapshot.config.mappings.state !== "invalidating") return snapshot;
539
- if (!ctx.resolver) {
540
- return {
541
- ...snapshot,
542
- config: { mappings: snapshot.config.mappings.previous }
543
- };
544
- }
545
- const outcome = ctx.resolver.current();
546
- if (outcome.kind !== "resolved") {
547
- return {
548
- ...snapshot,
549
- config: { mappings: snapshot.config.mappings.previous }
550
- };
551
- }
552
- return applyResolved(snapshot, outcome.state);
553
- }
554
- case "MAPPING_TIMEOUT": {
555
- const previous = snapshot.config.mappings;
556
- if (previous.state !== "pending") return snapshot;
557
- return {
558
- ...snapshot,
559
- config: {
560
- mappings: {
561
- state: "unreported",
562
- declared: previous.declared,
563
- afterMs: action.atMs - previous.declaredAtMs
564
- }
565
- }
566
- };
567
- }
568
- }
569
- }
570
- function applyResolved(snapshot, resolved) {
571
- const existing = snapshot.config.mappings;
572
- if ((existing.state === "complete" || existing.state === "incomplete") && sameResolved(existing, resolved)) {
573
- return snapshot;
574
- }
575
- return { ...snapshot, config: { mappings: resolved } };
576
- }
577
- function sameResolved(a, b) {
578
- if (a.state !== b.state) return false;
579
- if (a.state !== "complete" && a.state !== "incomplete") return false;
580
- if (a.source !== b.source) return false;
581
- const ak = Object.keys(a.mappings);
582
- const bk = Object.keys(b.mappings);
583
- if (ak.length !== bk.length) return false;
584
- for (const k of ak) {
585
- const av = a.mappings[k];
586
- const bv = b.mappings[k];
587
- if (Array.isArray(av) && Array.isArray(bv)) {
588
- if (av.length !== bv.length) return false;
589
- for (let i = 0; i < av.length; i++) if (av[i] !== bv[i]) return false;
590
- } else if (av !== bv) {
591
- return false;
592
- }
593
- }
594
- return true;
595
- }
596
- function reduceStream(snapshot, action) {
597
- if (action.type === "CURRENT_TABLE_KNOWN" || action.type === "CURRENT_TABLE_REFRESH_START" || action.type === "CURRENT_TABLE_ERROR") {
598
- return snapshot;
599
- }
600
- const stream = action.stream;
601
- const current = snapshot.sync[stream];
602
- if (action.type === "STREAM_WARMING") {
603
- if (current.state === "warming" || current.state === "hot") return snapshot;
604
- return updateStream(snapshot, stream, { state: "warming", sinceMs: action.atMs });
605
- }
606
- if (action.type === "STREAM_STALE") {
607
- if (current.state !== "hot") return snapshot;
608
- return updateStream(snapshot, stream, {
609
- state: "stale",
610
- lastEventMs: current.lastEventMs,
611
- reason: action.reason
612
- });
613
- }
614
- if (current.state === "hot" && current.generation === action.generation && current.payloadHash === action.payloadHash) {
615
- return snapshot;
616
- }
617
- return updateStream(snapshot, stream, {
618
- state: "hot",
619
- lastEventMs: action.atMs,
620
- generation: action.generation,
621
- payloadHash: action.payloadHash
622
- });
623
- }
624
- function updateStream(snapshot, stream, next) {
625
- return {
626
- ...snapshot,
627
- sync: { ...snapshot.sync, [stream]: next }
628
- };
629
- }
630
- function updateSync(snapshot, sync) {
631
- return { ...snapshot, sync };
632
- }
633
-
634
- // src/sdk/internal/handshake/derive.ts
635
- function deriveStatus(snapshot) {
636
- const { lifecycle, authz, link } = snapshot;
637
- if (lifecycle.phase === "idle" || lifecycle.phase === "detecting") return "booting";
638
- if (lifecycle.phase === "negotiating") return "booting";
639
- if (lifecycle.phase === "terminated") {
640
- switch (lifecycle.reason.kind) {
641
- case "script_timeout":
642
- case "not_embedded":
643
- return "unavailable";
644
- case "host_rejected":
645
- case "ready_failed":
646
- case "ready_timeout":
647
- case "manual_terminate":
648
- return "error";
649
- }
650
- }
651
- if (authz.state === "denied") return "error";
652
- if (link.state === "lost") return "error";
653
- return "ready";
654
- }
655
- function deriveErrorMessage(snapshot) {
656
- if (snapshot.lifecycle.phase === "terminated") {
657
- switch (snapshot.lifecycle.reason.kind) {
658
- case "ready_failed":
659
- return snapshot.lifecycle.reason.message;
660
- case "ready_timeout":
661
- return `Grist handshake timed out after ${snapshot.lifecycle.reason.afterMs}ms`;
662
- case "host_rejected":
663
- return snapshot.lifecycle.reason.message;
664
- case "script_timeout":
665
- return `Grist plugin API never loaded (${snapshot.lifecycle.reason.attempts} attempts)`;
666
- case "not_embedded":
667
- return "This page is not embedded in a Grist iframe";
668
- case "manual_terminate":
669
- return null;
670
- }
671
- }
672
- if (snapshot.authz.state === "denied") {
673
- return snapshot.authz.message ?? `Grist denied requested access (${snapshot.authz.declared})`;
674
- }
675
- if (snapshot.lifecycle.phase === "online" && snapshot.link.state === "lost") {
676
- return `Grist link lost (${snapshot.link.missedPings} consecutive failures)`;
677
- }
678
- return null;
679
- }
680
- function deriveCapabilities(snapshot) {
681
- const { lifecycle, authz, link, config, sync } = snapshot;
682
- const online = lifecycle.phase === "online";
683
- const granted = authz.state === "granted";
684
- const grantedReadOrMore = granted && ACCESS_RANK[authz.level] >= ACCESS_RANK["read table"];
685
- const grantedFull = granted && authz.level === "full";
686
- const linkUsable = link.state !== "lost";
687
- const canRead = online && linkUsable && grantedReadOrMore;
688
- const canFetchTable = canRead && link.state === "connected";
689
- const mappingsUsable = hasUsableMappings(config.mappings);
690
- const missing = mappingsMissing(config.mappings);
691
- const emptyMultiples = mappingsEmptyMultiples(config.mappings);
692
- const canRender = canRead && mappingsUsable;
693
- const canWriteRecords = canRender && grantedFull;
694
- const canWriteSchema = canWriteRecords && sync.currentTable.state === "known";
695
- const hasFreshSelection = canRead && sync.record.state === "hot" && config.mappings.state !== "invalidating";
696
- return {
697
- canRead,
698
- canRender,
699
- canWriteRecords,
700
- canWriteSchema,
701
- canFetchTable,
702
- hasFreshSelection,
703
- hasUsableMappings: mappingsUsable,
704
- missingMappings: missing,
705
- emptyMultipleMappings: emptyMultiples
706
- };
707
- }
708
- function hasUsableMappings(state) {
709
- if (state.state === "not_declared") return true;
710
- if (state.state === "complete") return true;
711
- if (state.state === "invalidating") {
712
- return state.previous.state === "complete";
713
- }
714
- return false;
715
- }
716
- function mappingsMissing(state) {
717
- if (state.state === "incomplete") return state.missing;
718
- if (state.state === "invalidating" && state.previous.state === "incomplete") {
719
- return state.previous.missing;
720
- }
721
- return EMPTY;
722
- }
723
- function mappingsEmptyMultiples(state) {
724
- if (state.state === "incomplete") return state.emptyMultiples;
725
- if (state.state === "invalidating" && state.previous.state === "incomplete") {
726
- return state.previous.emptyMultiples;
727
- }
728
- return EMPTY;
729
- }
730
- var EMPTY = Object.freeze([]);
731
- function extractResolvedMappings(state) {
732
- switch (state.state) {
733
- case "complete":
734
- case "incomplete":
735
- return state.mappings;
736
- case "invalidating":
737
- if (state.previous.state === "complete" || state.previous.state === "incomplete") {
738
- return state.previous.mappings;
739
- }
740
- return null;
741
- default:
742
- return null;
743
- }
744
- }
745
- function deriveColumnMappingStatus(mappingState, columns) {
746
- if (!columns?.length) {
747
- return { ok: true, pending: false, missing: [], emptyMultiples: [] };
748
- }
749
- switch (mappingState.state) {
750
- case "not_declared":
751
- return { ok: true, pending: false, missing: [], emptyMultiples: [] };
752
- case "pending":
753
- return pendingColumnMappingStatus;
754
- case "unreported":
755
- return pendingColumnMappingStatus;
756
- case "complete":
757
- return { ok: true, pending: false, missing: [], emptyMultiples: [] };
758
- case "incomplete":
759
- return {
760
- ok: false,
761
- pending: false,
762
- missing: [...mappingState.missing],
763
- emptyMultiples: [...mappingState.emptyMultiples]
764
- };
765
- case "invalidating":
766
- return deriveColumnMappingStatus(mappingState.previous, columns);
767
- }
768
- }
769
-
770
- // src/sdk/internal/handshake-manager-context.ts
771
- import { createContext, useContext, useEffect, useRef } from "react";
772
-
773
- // src/sdk/internal/ready-singleton.ts
774
- var ACCESS_RANK2 = {
775
- none: 0,
776
- "read table": 1,
777
- full: 2
778
- };
779
- var inFlight2 = null;
780
- var lastAccess = null;
781
- var lastColumnNames = null;
782
- function columnNamesOf(columns) {
783
- return new Set((columns ?? []).map((c) => typeof c === "string" ? c : c.name));
784
- }
785
- function shouldReinit(next, nextColumns) {
786
- if (!lastAccess) return true;
787
- if (ACCESS_RANK2[next] > ACCESS_RANK2[lastAccess]) return true;
788
- for (const name of nextColumns) {
789
- if (!lastColumnNames?.has(name)) return true;
790
- }
791
- return false;
792
- }
793
- function ensureGristReady(payload) {
794
- const access = payload.requiredAccess ?? "read table";
795
- const columns = columnNamesOf(payload.columns);
796
- if (inFlight2 && !shouldReinit(access, columns)) return inFlight2;
797
- lastAccess = access;
798
- lastColumnNames = columns;
799
- const next = Promise.resolve().then(() => {
800
- const result = grist.ready(payload);
801
- return result instanceof Promise ? result : Promise.resolve();
802
- });
803
- inFlight2 = next.catch((err) => {
804
- inFlight2 = null;
805
- lastAccess = null;
806
- lastColumnNames = null;
807
- throw err;
808
- });
809
- return inFlight2;
810
- }
811
- function resetGristReadySingleton() {
812
- inFlight2 = null;
813
- lastAccess = null;
814
- lastColumnNames = null;
815
- }
816
- var resetGristReadyCacheForTests = resetGristReadySingleton;
817
-
818
- // src/sdk/internal/build-manager-options.ts
819
- function buildManagerOptionsFromGristOptions(options) {
820
- const opts = {
821
- requiredAccess: options?.requiredAccess ?? "read table",
822
- columns: options?.columns ?? [],
823
- allowSelectBy: options?.allowSelectBy,
824
- hasCustomOptions: options?.hasCustomOptions,
825
- onEditOptions: options?.onEditOptions,
826
- negotiate: {
827
- readyImpl: (payload) => ensureGristReady(payload)
828
- },
829
- onBeforeReload: () => resetGristReadySingleton()
830
- };
831
- if (options?.availabilityMaxAttempts !== void 0 || options?.availabilityIntervalMs !== void 0) {
832
- const interval = options?.availabilityIntervalMs ?? 1e3;
833
- const max = options?.availabilityMaxAttempts ?? 10;
834
- opts.detect = {
835
- pollSequenceMs: Array.from({ length: max }, () => interval),
836
- budgetMs: interval * max
837
- };
838
- }
839
- return opts;
840
- }
841
-
842
- // src/sdk/internal/handshake/effects/detect.ts
843
- var DEFAULT_POLL_SEQUENCE_MS = [
844
- 200,
845
- 200,
846
- 400,
847
- 400,
848
- 800,
849
- 1600,
850
- 3200,
851
- 5e3,
852
- 5e3,
853
- 5e3,
854
- 5e3,
855
- 5e3,
856
- 5e3,
857
- 5e3
858
- ];
859
- function defaultBudgetMs(hint) {
860
- if (hint === "slow-2g" || hint === "2g") return 12e4;
861
- if (hint === "3g") return 6e4;
862
- return 3e4;
863
- }
864
- function startDetectEffect(env, dispatch, signal, options = {}) {
865
- const sequence = options.pollSequenceMs ?? DEFAULT_POLL_SEQUENCE_MS;
866
- const budgetMs = options.budgetMs ?? defaultBudgetMs(env.effectiveTypeHint());
867
- const startedAt = env.now();
868
- let attempts = 0;
869
- let timer = null;
870
- let cancelled = false;
871
- signal.addEventListener("abort", () => {
872
- cancelled = true;
873
- if (timer !== null) env.clearTimeout(timer);
874
- });
875
- dispatch({ type: "DETECT_START", atMs: startedAt });
876
- const tick = () => {
877
- if (cancelled) return;
878
- timer = null;
879
- const probe = env.probeGrist();
880
- if (probe !== null) {
881
- if (probe.embedded) {
882
- dispatch({ type: "DETECT_AVAILABLE", atMs: env.now() });
883
- } else {
884
- dispatch({ type: "NOT_EMBEDDED", atMs: env.now() });
885
- }
886
- return;
887
- }
888
- attempts += 1;
889
- dispatch({ type: "DETECT_TICK", attempts, atMs: env.now() });
890
- const elapsed = env.now() - startedAt;
891
- if (elapsed >= budgetMs) {
892
- dispatch({ type: "DETECT_TIMEOUT", attempts, atMs: env.now() });
893
- return;
894
- }
895
- const next = sequence[Math.min(attempts - 1, sequence.length - 1)] ?? 1e3;
896
- const remaining = budgetMs - elapsed;
897
- timer = env.setTimeout(tick, Math.max(0, Math.min(next, remaining)));
898
- };
899
- tick();
900
- return {
901
- cancel() {
902
- cancelled = true;
903
- if (timer !== null) {
904
- env.clearTimeout(timer);
905
- timer = null;
906
- }
907
- }
908
- };
909
- }
910
-
911
- // src/sdk/internal/handshake/effects/negotiate.ts
912
- var DEFAULT_NEGOTIATE_TIMEOUT_MS = 3e4;
913
- function startNegotiateEffect(env, dispatch, signal, payload, options = {}) {
914
- const timeoutMs = options.timeoutMs ?? DEFAULT_NEGOTIATE_TIMEOUT_MS;
915
- const access = payload.requiredAccess ?? "read table";
916
- let settled = false;
917
- let timer = null;
918
- const settle = (next) => {
919
- if (settled) return;
920
- settled = true;
921
- if (timer !== null) env.clearTimeout(timer);
922
- if (signal.aborted) return;
923
- next();
924
- };
925
- dispatch({ type: "NEGOTIATE_START", access, atMs: env.now() });
926
- const grist2 = env.getGrist();
927
- if (!grist2) {
928
- settle(
929
- () => dispatch({
930
- type: "NEGOTIATE_FAIL",
931
- reason: { kind: "ready_failed", message: "grist global missing at negotiate" },
932
- atMs: env.now()
933
- })
934
- );
935
- return { cancel: () => settle(() => {
936
- }) };
937
- }
938
- timer = env.setTimeout(() => {
939
- if (settled) return;
940
- settle(
941
- () => dispatch({
942
- type: "NEGOTIATE_FAIL",
943
- reason: { kind: "ready_timeout", afterMs: timeoutMs },
944
- atMs: env.now()
945
- })
946
- );
947
- }, timeoutMs);
948
- const handleSuccess = (g) => {
949
- if (!g.docApi) {
950
- dispatch({
951
- type: "NEGOTIATE_FAIL",
952
- reason: { kind: "ready_failed", message: "grist.docApi missing after ready" },
953
- atMs: env.now()
954
- });
955
- return;
956
- }
957
- dispatch({
958
- type: "NEGOTIATE_SUCCESS",
959
- access,
960
- grantedLevel: access,
961
- // host doesn't report effective level; widen later via authz events
962
- atMs: env.now()
963
- });
964
- };
965
- const handleFailure = (err) => {
966
- const message = err instanceof Error ? err.message : String(err);
967
- const reason = { kind: "ready_failed", message };
968
- dispatch({ type: "NEGOTIATE_FAIL", reason, atMs: env.now() });
969
- };
970
- const readyImpl = options.readyImpl ?? ((p) => grist2.ready(p));
971
- try {
972
- const result = readyImpl(payload);
973
- if (result && typeof result.then === "function") {
974
- ;
975
- result.then(
976
- () => settle(() => handleSuccess(env.getGrist() ?? grist2)),
977
- (err) => settle(() => handleFailure(err))
978
- );
979
- } else {
980
- settle(() => handleSuccess(env.getGrist() ?? grist2));
981
- }
982
- } catch (err) {
983
- settle(() => handleFailure(err));
984
- }
985
- signal.addEventListener("abort", () => settle(() => {
986
- }));
987
- return { cancel: () => settle(() => {
988
- }) };
989
- }
990
-
991
- // src/sdk/helpers/grist-widget-interaction.ts
992
- function parseGristWidgetLinkingInfo(raw) {
993
- if (!raw || typeof raw !== "object" || !("asTarget" in raw)) return void 0;
994
- const linking = raw;
995
- return {
996
- asTarget: linking.asTarget == null ? null : String(linking.asTarget),
997
- asSource: Boolean(linking.asSource)
998
- };
999
- }
1000
- function normalizeWidgetInteraction(interaction) {
1001
- if (!interaction || typeof interaction !== "object") return interaction;
1002
- const raw = interaction;
1003
- const access_level = typeof raw.access_level === "string" ? raw.access_level : typeof raw.accessLevel === "string" ? raw.accessLevel : void 0;
1004
- const linking = parseGristWidgetLinkingInfo(raw.linking);
1005
- return {
1006
- ...interaction,
1007
- ...access_level ? { access_level } : {},
1008
- ...linking ? { linking } : {}
1009
- };
1010
- }
1011
-
1012
- // src/sdk/internal/subscriptions.ts
1013
- var GristEvent = class {
1014
- constructor(bindOnce) {
1015
- this.bindOnce = bindOnce;
1016
- this.listeners = /* @__PURE__ */ new Set();
1017
- this.hasValue = false;
1018
- this.bind = null;
1019
- }
1020
- subscribe(listener) {
1021
- this.listeners.add(listener);
1022
- if (!this.bind) {
1023
- this.bind = () => {
1024
- this.bind = () => {
1025
- };
1026
- try {
1027
- this.bindOnce((value) => {
1028
- this.hasValue = true;
1029
- this.last = value;
1030
- for (const l of this.listeners) l(value);
1031
- });
1032
- } catch (err) {
1033
- if (typeof console !== "undefined") {
1034
- console.error("[lib/grist] failed to subscribe to Grist event:", err);
1035
- }
1036
- }
1037
- };
1038
- this.bind();
1039
- }
1040
- if (this.hasValue && this.last !== void 0) {
1041
- listener(this.last);
1042
- }
1043
- return () => {
1044
- this.listeners.delete(listener);
1045
- };
1046
- }
1047
- /** Last cached value (or `undefined` if no event has fired yet). */
1048
- peek() {
1049
- return this.last;
1050
- }
1051
- /** True once at least one event has fired. */
1052
- get ready() {
1053
- return this.hasValue;
1054
- }
1055
- /**
1056
- * Test helper: fan out a payload without calling `grist.on*`.
1057
- * Used to simulate hosts that reuse one record object and mutate it in place.
1058
- */
1059
- deliverForTests(value) {
1060
- this.hasValue = true;
1061
- this.last = value;
1062
- for (const l of this.listeners) l(value);
1063
- }
1064
- /**
1065
- * Test helper: forget the bound state and cached value. Lets a test swap
1066
- * `window.grist` (e.g. via the emulator's `dispose()` + `createGristEmulator()`)
1067
- * and re-bind cleanly on the next subscribe.
1068
- */
1069
- _resetForTests() {
1070
- this.listeners.clear();
1071
- this.hasValue = false;
1072
- this.last = void 0;
1073
- this.bind = null;
1074
- }
1075
- };
1076
- var recordEvent = new GristEvent((emit) => {
1077
- const deliver = (record, mappings) => {
1078
- emit({ record, mappings });
1079
- };
1080
- grist.onRecord(
1081
- (record, mappings) => {
1082
- deliver(record, mappings ?? null);
1083
- },
1084
- { keepEncoded: false }
1085
- );
1086
- const fetchSelectedRecord = grist.fetchSelectedRecord ?? grist.docApi?.fetchSelectedRecord;
1087
- if (typeof grist.on !== "function" || typeof fetchSelectedRecord !== "function") {
1088
- return;
1089
- }
1090
- let lastRowId;
1091
- grist.on("message", async (msg) => {
1092
- if (!msg || typeof msg !== "object") return;
1093
- const host = msg;
1094
- if (!host.tableId || typeof host.rowId !== "number") return;
1095
- if (host.rowId === lastRowId) return;
1096
- lastRowId = host.rowId;
1097
- try {
1098
- const record = await fetchSelectedRecord(host.rowId, { keepEncoded: false });
1099
- deliver(record, recordEvent.peek()?.mappings ?? null);
1100
- } catch (err) {
1101
- if (typeof console !== "undefined") {
1102
- console.error("[grist-widget-sdk] fetchSelectedRecord on cursor message failed:", err);
1103
- }
1104
- }
1105
- });
1106
- });
1107
- var recordsEvent = new GristEvent((emit) => {
1108
- grist.onRecords(
1109
- (records, mappings) => {
1110
- emit({ records, mappings: mappings ?? null });
1111
- },
1112
- { keepEncoded: false, format: "rows" }
1113
- );
1114
- });
1115
- var optionsEvent = new GristEvent((emit) => {
1116
- grist.onOptions((options, interaction) => {
1117
- const normalized = normalizeWidgetInteraction(
1118
- interaction ?? null
1119
- );
1120
- emit({
1121
- options: options ? { ...options } : null,
1122
- interaction: normalized
1123
- });
1124
- });
1125
- });
1126
- var newRecordEvent = new GristEvent((emit) => {
1127
- if (typeof grist.onNewRecord !== "function") return;
1128
- grist.onNewRecord((mappings) => {
1129
- emit({ mappings: mappings ?? null });
1130
- });
1131
- });
1132
- function resetGristEventsForTests() {
1133
- recordEvent._resetForTests();
1134
- recordsEvent._resetForTests();
1135
- optionsEvent._resetForTests();
1136
- newRecordEvent._resetForTests();
1137
- }
1138
-
1139
- // src/sdk/internal/handshake/effects/subscriptions.ts
1140
- function defaultSubscriptionsBinder(ctx) {
1141
- const offs = [];
1142
- offs.push(
1143
- recordEvent.subscribe((payload) => {
1144
- const hash = quickHash("record", payload);
1145
- dispatchStream(ctx, "record", hash);
1146
- ctx.onRecordPayload?.(payload.mappings ?? null);
1147
- })
1148
- );
1149
- offs.push(
1150
- recordsEvent.subscribe((payload) => {
1151
- const hash = quickHash("records", payload);
1152
- dispatchStream(ctx, "records", hash);
1153
- ctx.onRecordsPayload?.(payload.mappings ?? null);
1154
- })
1155
- );
1156
- offs.push(
1157
- optionsEvent.subscribe((payload) => {
1158
- const hash = quickHash("options", payload);
1159
- dispatchStream(ctx, "options", hash);
1160
- const level = parseGristRequiredAccess(payload.interaction?.access_level);
1161
- if (level !== null) {
1162
- ctx.dispatch({
1163
- type: "AUTHZ_REPORT",
1164
- level,
1165
- atMs: Date.now(),
1166
- generation: ctx.getGeneration()
1167
- });
1168
- }
1169
- ctx.onOptionsPayload?.(payload.options ?? null);
1170
- })
1171
- );
1172
- offs.push(
1173
- newRecordEvent.subscribe((payload) => {
1174
- const hash = quickHash("newRecord", payload);
1175
- dispatchStream(ctx, "newRecord", hash);
1176
- ctx.onNewRecordPayload?.(payload.mappings ?? null);
1177
- })
1178
- );
1179
- return {
1180
- cancel() {
1181
- for (const off of offs.splice(0)) off();
1182
- }
1183
- };
1184
- }
1185
- function dispatchStream(ctx, stream, payloadHash) {
1186
- ctx.dispatch({
1187
- type: "STREAM_RECEIVED",
1188
- stream,
1189
- payloadHash,
1190
- atMs: Date.now(),
1191
- generation: ctx.getGeneration()
1192
- });
1193
- }
1194
- function quickHash(kind, payload) {
1195
- return `${kind}::${stableSerialize(payload)}`;
1196
- }
1197
- function stableSerialize(value) {
1198
- if (value === null) return "null";
1199
- if (value === void 0) return "undefined";
1200
- const t = typeof value;
1201
- if (t === "number" || t === "string" || t === "boolean") return JSON.stringify(value);
1202
- if (Array.isArray(value)) {
1203
- return `[${value.map(stableSerialize).join(",")}]`;
1204
- }
1205
- if (t === "object") {
1206
- const obj = value;
1207
- const keys = Object.keys(obj).sort();
1208
- const body = keys.map((k) => `${JSON.stringify(k)}:${stableSerialize(obj[k])}`).join(",");
1209
- return `{${body}}`;
1210
- }
1211
- return String(value);
1212
- }
1213
-
1214
- // src/sdk/internal/handshake/effects/mappings.ts
1215
- var DEFAULT_MAPPING_TIMEOUT_MS = 5e3;
1216
- function startMappingsEffect(env, dispatch, signal, declared, getGeneration, options = {}) {
1217
- let timeoutHandle = null;
1218
- let cancelled = false;
1219
- const startMs = env.now();
1220
- dispatch({ type: "MAPPING_DECLARE", declared, atMs: startMs, generation: getGeneration() });
1221
- if (declared.length === 0) {
1222
- return {
1223
- ingestStreamPayload: () => {
1224
- },
1225
- refetchSectionApi: async () => {
1226
- },
1227
- cancel: () => {
1228
- }
1229
- };
1230
- }
1231
- const timeoutMs = options.timeoutMs ?? DEFAULT_MAPPING_TIMEOUT_MS;
1232
- timeoutHandle = env.setTimeout(() => {
1233
- if (cancelled || signal.aborted) return;
1234
- dispatch({ type: "MAPPING_TIMEOUT", atMs: env.now(), generation: getGeneration() });
1235
- }, timeoutMs);
1236
- signal.addEventListener("abort", () => {
1237
- cancelled = true;
1238
- if (timeoutHandle !== null) env.clearTimeout(timeoutHandle);
1239
- });
1240
- const ingestPayload = (source, raw) => {
1241
- if (cancelled || signal.aborted) return;
1242
- const payload = coerceMappingsPayload(raw);
1243
- dispatch({
1244
- type: "MAPPING_REPORT",
1245
- source,
1246
- payload,
1247
- atMs: env.now(),
1248
- generation: getGeneration()
1249
- });
1250
- };
1251
- const refetchSectionApi = async () => {
1252
- if (cancelled || signal.aborted) return;
1253
- const grist2 = env.getGrist();
1254
- const api = grist2?.sectionApi;
1255
- if (!api || typeof api.mappings !== "function") return;
1256
- try {
1257
- const payload = await api.mappings();
1258
- ingestPayload("section_api", payload);
1259
- } catch {
1260
- ingestPayload("section_api", null);
1261
- }
1262
- };
1263
- void refetchSectionApi();
1264
- return {
1265
- ingestStreamPayload: (source, payload) => ingestPayload(source, payload),
1266
- refetchSectionApi,
1267
- cancel() {
1268
- cancelled = true;
1269
- if (timeoutHandle !== null) env.clearTimeout(timeoutHandle);
1270
- }
1271
- };
1272
- }
1273
- function coerceMappingsPayload(raw) {
1274
- if (raw === null || raw === void 0) return null;
1275
- if (typeof raw !== "object") return null;
1276
- return raw;
1277
- }
1278
-
1279
- // src/sdk/internal/handshake/effects/heartbeat.ts
1280
- var DEFAULT_HEARTBEAT_INTERVAL_MS = 3e4;
1281
- var DEFAULT_HEARTBEAT_PING_TIMEOUT_MS = 1e4;
1282
- function startHeartbeatEffect(env, dispatch, signal, options = {}) {
1283
- const intervalMs = options.intervalMs ?? DEFAULT_HEARTBEAT_INTERVAL_MS;
1284
- const pingTimeoutMs = options.pingTimeoutMs ?? DEFAULT_HEARTBEAT_PING_TIMEOUT_MS;
1285
- const pauseWhenHidden = options.pauseWhenHidden ?? true;
1286
- const probe = options.probe ?? defaultProbe(env);
1287
- let cancelled = false;
1288
- let paused = false;
1289
- let intervalTimer = null;
1290
- let inFlight3 = false;
1291
- let inFlightTimeoutTimer = null;
1292
- const clearInterval = () => {
1293
- if (intervalTimer !== null) {
1294
- env.clearTimeout(intervalTimer);
1295
- intervalTimer = null;
1296
- }
1297
- };
1298
- const clearInFlightTimeout = () => {
1299
- if (inFlightTimeoutTimer !== null) {
1300
- env.clearTimeout(inFlightTimeoutTimer);
1301
- inFlightTimeoutTimer = null;
1302
- }
1303
- };
1304
- const scheduleNext = (delay = intervalMs) => {
1305
- clearInterval();
1306
- if (cancelled || paused) return;
1307
- intervalTimer = env.setTimeout(ping, delay);
1308
- };
1309
- const ping = () => {
1310
- if (cancelled || paused) return;
1311
- intervalTimer = null;
1312
- if (inFlight3) {
1313
- return;
1314
- }
1315
- inFlight3 = true;
1316
- inFlightTimeoutTimer = env.setTimeout(() => {
1317
- if (!inFlight3) return;
1318
- inFlight3 = false;
1319
- clearInFlightTimeout();
1320
- if (!cancelled) {
1321
- dispatch({ type: "HEARTBEAT_FAIL", atMs: env.now() });
1322
- scheduleNext();
1323
- }
1324
- }, pingTimeoutMs);
1325
- const handleOk = () => {
1326
- if (!inFlight3) return;
1327
- inFlight3 = false;
1328
- clearInFlightTimeout();
1329
- if (cancelled) return;
1330
- dispatch({ type: "HEARTBEAT_OK", atMs: env.now() });
1331
- scheduleNext();
1332
- };
1333
- const handleFail = () => {
1334
- if (!inFlight3) return;
1335
- inFlight3 = false;
1336
- clearInFlightTimeout();
1337
- if (cancelled) return;
1338
- dispatch({ type: "HEARTBEAT_FAIL", atMs: env.now() });
1339
- scheduleNext();
1340
- };
1341
- let result;
1342
- try {
1343
- result = probe();
1344
- } catch {
1345
- handleFail();
1346
- return;
1347
- }
1348
- if (result && typeof result.then === "function") {
1349
- ;
1350
- result.then(handleOk, handleFail);
1351
- } else {
1352
- handleOk();
1353
- }
1354
- };
1355
- const offVisibility = pauseWhenHidden && env.onVisibilityChange ? env.onVisibilityChange((visible) => {
1356
- if (cancelled) return;
1357
- if (visible) {
1358
- if (paused) {
1359
- paused = false;
1360
- ping();
1361
- }
1362
- } else {
1363
- paused = true;
1364
- clearInterval();
1365
- }
1366
- }) : null;
1367
- const offOnline = env.onOnline?.(() => {
1368
- if (cancelled || paused) return;
1369
- ping();
1370
- }) ?? null;
1371
- signal.addEventListener("abort", () => {
1372
- cancelled = true;
1373
- clearInterval();
1374
- clearInFlightTimeout();
1375
- inFlight3 = false;
1376
- offVisibility?.();
1377
- offOnline?.();
1378
- });
1379
- scheduleNext();
1380
- return {
1381
- cancel() {
1382
- cancelled = true;
1383
- clearInterval();
1384
- clearInFlightTimeout();
1385
- inFlight3 = false;
1386
- offVisibility?.();
1387
- offOnline?.();
1388
- },
1389
- recordRpcSuccess() {
1390
- if (cancelled || paused) return;
1391
- dispatch({ type: "RPC_SUCCESS", atMs: env.now() });
1392
- scheduleNext();
1393
- },
1394
- recordRpcFailure() {
1395
- if (cancelled || paused) return;
1396
- dispatch({ type: "RPC_FAILURE", atMs: env.now(), kind: "other" });
1397
- scheduleNext(Math.min(intervalMs, 1e3));
1398
- },
1399
- pingNow() {
1400
- if (cancelled) return;
1401
- ping();
1402
- }
1403
- };
1404
- }
1405
- function defaultProbe(env) {
1406
- return async () => {
1407
- const g = env.getGrist();
1408
- if (!g) throw new Error("grist global missing");
1409
- const docApi = g.docApi;
1410
- if (!docApi || typeof docApi.getDocName !== "function") {
1411
- throw new Error("grist.docApi.getDocName unavailable");
1412
- }
1413
- return docApi.getDocName();
1414
- };
1415
- }
1416
-
1417
- // src/sdk/internal/handshake/authz-from-options-cache.ts
1418
- function denyAuthzFromCachedOptionsIfInsufficient(snapshot, dispatch, env) {
1419
- if (snapshot.lifecycle.phase !== "online") return;
1420
- if (snapshot.authz.state === "denied") return;
1421
- const payload = optionsEvent.peek();
1422
- const level = parseGristRequiredAccess(payload?.interaction?.access_level);
1423
- if (level === null) return;
1424
- const declared = snapshot.authz.declared;
1425
- if (isAccessSufficient(level, declared)) return;
1426
- dispatch({
1427
- type: "AUTHZ_REPORT",
1428
- level,
1429
- atMs: env.now(),
1430
- generation: snapshot.generation
1431
- });
1432
- }
1433
-
1434
- // src/sdk/internal/handshake/environment.ts
1435
- function createBrowserEnvironment() {
1436
- return {
1437
- now: () => typeof performance !== "undefined" ? performance.now() : Date.now(),
1438
- setTimeout: (cb, ms) => globalThis.setTimeout(cb, ms),
1439
- clearTimeout: (h) => globalThis.clearTimeout(h),
1440
- probeGrist() {
1441
- if (typeof globalThis === "undefined") return null;
1442
- const g = globalThis.grist;
1443
- if (typeof g === "undefined") return null;
1444
- const embedded2 = typeof window === "undefined" ? false : window.self !== window.top;
1445
- return { embedded: embedded2 };
1446
- },
1447
- getGrist() {
1448
- const g = globalThis.grist;
1449
- return g ?? null;
1450
- },
1451
- effectiveTypeHint() {
1452
- if (typeof navigator === "undefined") return null;
1453
- const conn = navigator.connection;
1454
- const t = conn?.effectiveType;
1455
- if (t === "slow-2g" || t === "2g" || t === "3g" || t === "4g" || t === "5g") return t;
1456
- return null;
1457
- },
1458
- onVisibilityChange(listener) {
1459
- if (typeof document === "undefined") return () => {
1460
- };
1461
- const handler = () => listener(document.visibilityState === "visible");
1462
- document.addEventListener("visibilitychange", handler);
1463
- return () => document.removeEventListener("visibilitychange", handler);
1464
- },
1465
- onOnline(listener) {
1466
- if (typeof window === "undefined") return () => {
1467
- };
1468
- const handler = () => listener();
1469
- window.addEventListener("online", handler);
1470
- return () => window.removeEventListener("online", handler);
1471
- }
1472
- };
1473
- }
1474
-
1475
- // src/sdk/internal/handshake/manager.ts
1476
- function createGristHandshakeManager(options = {}) {
1477
- const env = options.env ?? createBrowserEnvironment();
1478
- const reducerConfig = {
1479
- ...DEFAULT_REDUCER_CONFIG,
1480
- ...options.reducerConfig ?? {}
1481
- };
1482
- let snapshot = initialGristSnapshot();
1483
- const ctx = createReducerContext();
1484
- const listeners = /* @__PURE__ */ new Set();
1485
- let started = false;
1486
- let abort = null;
1487
- let detectHandle = null;
1488
- let negotiateHandle = null;
1489
- let subscriptionsHandle = null;
1490
- let mappingsHandle = null;
1491
- let heartbeatHandle = null;
1492
- let recheckAuthzFromCacheAfterOnline = false;
1493
- const declared = options.columns ?? [];
1494
- const subscriptionsBinder = options.subscriptionsBinder ?? defaultSubscriptionsBinder;
1495
- const notify = () => {
1496
- for (const l of listeners) {
1497
- try {
1498
- l();
1499
- } catch (err) {
1500
- options.onError?.(err, "listener");
1501
- }
1502
- }
1503
- };
1504
- const dispatch = (action) => {
1505
- const prev = snapshot;
1506
- const next = gristReducer(prev, action, ctx, reducerConfig);
1507
- if (next !== prev) {
1508
- snapshot = next;
1509
- onTransition(prev, next);
1510
- notify();
1511
- }
1512
- };
1513
- const onTransition = (prev, next) => {
1514
- if (prev.lifecycle.phase !== "negotiating" && next.lifecycle.phase === "negotiating") {
1515
- launchNegotiate();
1516
- launchSubscriptions();
1517
- }
1518
- if (prev.lifecycle.phase !== "online" && next.lifecycle.phase === "online") {
1519
- launchMappings();
1520
- launchHeartbeat();
1521
- if (recheckAuthzFromCacheAfterOnline) {
1522
- recheckAuthzFromCacheAfterOnline = false;
1523
- denyAuthzFromCachedOptionsIfInsufficient(next, dispatch, env);
1524
- }
1525
- }
1526
- if (prev.lifecycle.phase === "online" && next.lifecycle.phase !== "online") {
1527
- heartbeatHandle?.cancel();
1528
- heartbeatHandle = null;
1529
- }
1530
- };
1531
- const launchDetect = () => {
1532
- if (!abort) return;
1533
- detectHandle?.cancel();
1534
- detectHandle = startDetectEffect(env, dispatch, abort.signal, options.detect);
1535
- };
1536
- const launchNegotiate = () => {
1537
- if (!abort) return;
1538
- negotiateHandle?.cancel();
1539
- negotiateHandle = startNegotiateEffect(
1540
- env,
1541
- dispatch,
1542
- abort.signal,
1543
- buildReadyPayload(options),
1544
- options.negotiate
1545
- );
1546
- };
1547
- const launchSubscriptions = () => {
1548
- if (!abort) return;
1549
- if (subscriptionsHandle) return;
1550
- subscriptionsHandle = subscriptionsBinder({
1551
- dispatch,
1552
- getGeneration: () => snapshot.generation,
1553
- onRecordPayload: (m) => mappingsHandle?.ingestStreamPayload("stream_record", m),
1554
- onRecordsPayload: (m) => mappingsHandle?.ingestStreamPayload("stream_records", m),
1555
- onNewRecordPayload: (m) => mappingsHandle?.ingestStreamPayload("stream_new_record", m)
1556
- });
1557
- };
1558
- const launchMappings = () => {
1559
- if (!abort) return;
1560
- launchSubscriptions();
1561
- if (mappingsHandle) return;
1562
- mappingsHandle = startMappingsEffect(
1563
- env,
1564
- dispatch,
1565
- abort.signal,
1566
- declared,
1567
- () => snapshot.generation,
1568
- options.mappings
1569
- );
1570
- };
1571
- const launchHeartbeat = () => {
1572
- if (!abort) return;
1573
- if (options.heartbeat === false) return;
1574
- if (heartbeatHandle) return;
1575
- heartbeatHandle = startHeartbeatEffect(
1576
- env,
1577
- dispatch,
1578
- abort.signal,
1579
- options.heartbeat ?? {}
1580
- );
1581
- };
1582
- const cancelAllEffects = () => {
1583
- detectHandle?.cancel();
1584
- detectHandle = null;
1585
- negotiateHandle?.cancel();
1586
- negotiateHandle = null;
1587
- mappingsHandle?.cancel();
1588
- mappingsHandle = null;
1589
- heartbeatHandle?.cancel();
1590
- heartbeatHandle = null;
1591
- if (abort && !abort.signal.aborted) abort.abort();
1592
- };
1593
- const controls = {
1594
- start() {
1595
- if (started) return;
1596
- started = true;
1597
- abort = new AbortController();
1598
- launchDetect();
1599
- },
1600
- stop() {
1601
- if (!started) return;
1602
- started = false;
1603
- cancelAllEffects();
1604
- subscriptionsHandle?.cancel();
1605
- subscriptionsHandle = null;
1606
- snapshot = initialGristSnapshot();
1607
- notify();
1608
- },
1609
- reload() {
1610
- if (!started) {
1611
- controls.start();
1612
- return;
1613
- }
1614
- recheckAuthzFromCacheAfterOnline = true;
1615
- try {
1616
- options.onBeforeReload?.();
1617
- } catch (err) {
1618
- options.onError?.(err, "onBeforeReload");
1619
- }
1620
- cancelAllEffects();
1621
- dispatch({ type: "BUMP_GENERATION", atMs: env.now(), reason: "reload" });
1622
- snapshot = {
1623
- ...initialGristSnapshot(),
1624
- generation: nextGeneration(snapshot.generation)
1625
- };
1626
- ctx.resolver = null;
1627
- abort = new AbortController();
1628
- launchDetect();
1629
- notify();
1630
- },
1631
- restart() {
1632
- controls.reload();
1633
- if (typeof window !== "undefined" && typeof window.location?.reload === "function") {
1634
- try {
1635
- window.location.reload();
1636
- } catch (err) {
1637
- options.onError?.(err, "restart");
1638
- }
1639
- }
1640
- },
1641
- subscribe(listener) {
1642
- listeners.add(listener);
1643
- return () => listeners.delete(listener);
1644
- },
1645
- getSnapshot: () => snapshot,
1646
- dispatch,
1647
- recordRpcSuccess() {
1648
- heartbeatHandle?.recordRpcSuccess();
1649
- },
1650
- recordRpcFailure() {
1651
- heartbeatHandle?.recordRpcFailure();
1652
- }
1653
- };
1654
- return controls;
1655
- }
1656
- function buildReadyPayload(options) {
1657
- const payload = {
1658
- requiredAccess: options.requiredAccess ?? "read table",
1659
- columns: options.columns ?? []
1660
- };
1661
- if (options.allowSelectBy !== void 0) payload.allowSelectBy = options.allowSelectBy;
1662
- if (options.hasCustomOptions !== void 0) payload.hasCustomOptions = options.hasCustomOptions;
1663
- if (options.onEditOptions) payload.onEditOptions = options.onEditOptions;
1664
- return payload;
1665
- }
1666
-
1667
- // src/sdk/internal/embedded-handshake-manager.ts
1668
- var embedded = null;
1669
- function acquireEmbeddedHandshakeManager(options) {
1670
- if (!embedded) {
1671
- embedded = {
1672
- manager: createGristHandshakeManager(options),
1673
- refCount: 0
1674
- };
1675
- embedded.manager.start();
1676
- }
1677
- embedded.refCount += 1;
1678
- return embedded.manager;
1679
- }
1680
- function releaseEmbeddedHandshakeManager() {
1681
- if (!embedded) return;
1682
- embedded.refCount -= 1;
1683
- if (embedded.refCount <= 0) {
1684
- embedded.manager.stop();
1685
- embedded = null;
1686
- }
1687
- }
1688
- function resetEmbeddedHandshakeManagerForTests() {
1689
- if (embedded) {
1690
- embedded.manager.stop();
1691
- embedded = null;
1692
- }
1693
- }
1694
-
1695
- // src/sdk/internal/handshake-manager-context.ts
1696
- var GristHandshakeManagerContext = createContext(null);
1697
- function useGristManagerOptional() {
1698
- return useContext(GristHandshakeManagerContext);
1699
- }
1700
- function useGristManager(options) {
1701
- const fromProvider = useContext(GristHandshakeManagerContext);
1702
- const optionsRef = useRef(options);
1703
- optionsRef.current = options;
1704
- const embeddedRef = useRef(null);
1705
- const ownsEmbeddedRef = useRef(false);
1706
- if (fromProvider) {
1707
- return fromProvider;
1708
- }
1709
- if (embeddedRef.current === null) {
1710
- embeddedRef.current = acquireEmbeddedHandshakeManager(
1711
- buildManagerOptionsFromGristOptions(optionsRef.current)
1712
- );
1713
- ownsEmbeddedRef.current = true;
1714
- }
1715
- useEffect(() => {
1716
- if (!ownsEmbeddedRef.current) return;
1717
- return () => {
1718
- releaseEmbeddedHandshakeManager();
1719
- embeddedRef.current = null;
1720
- ownsEmbeddedRef.current = false;
1721
- };
1722
- }, []);
1723
- return embeddedRef.current;
1724
- }
1725
-
1726
- // src/sdk/internal/hooks/use-grist-core.ts
1727
- function computeAvailabilityFromSnapshot(snapshot) {
1728
- const { phase } = snapshot.lifecycle;
1729
- if (phase === "idle" || phase === "detecting") return null;
1730
- if (phase === "terminated") {
1731
- const reason = snapshot.lifecycle.reason.kind;
1732
- if (reason === "not_embedded" || reason === "script_timeout") return false;
1733
- return true;
1734
- }
1735
- return true;
1736
- }
1737
- function useGristCore(options) {
1738
- const manager = useGristManager(options);
1739
- return useGristCoreFromManager(manager);
1740
- }
1741
- function useGristCoreFromManager(manager) {
1742
- const snapshot = useSyncExternalStore(
1743
- manager.subscribe,
1744
- manager.getSnapshot,
1745
- initialGristSnapshot
1746
- );
1747
- const status = deriveStatus(snapshot);
1748
- const error = deriveErrorMessage(snapshot);
1749
- const docApi = snapshot.lifecycle.phase === "online" && typeof grist !== "undefined" ? grist.docApi ?? null : null;
1750
- const isAvailable = computeAvailabilityFromSnapshot(snapshot);
1751
- const reload = useCallback(async () => {
1752
- manager.reload();
1753
- }, [manager]);
1754
- const capabilities = useMemo(() => deriveCapabilities(snapshot), [snapshot]);
1755
- return useMemo(
1756
- () => ({
1757
- status,
1758
- isAvailable,
1759
- isReady: status === "ready",
1760
- error,
1761
- docApi,
1762
- capabilities,
1763
- reload
1764
- }),
1765
- [status, isAvailable, error, docApi, capabilities, reload]
1766
- );
1767
- }
1768
-
1769
- // src/sdk/low-level-hooks/use-grist-ready.ts
1770
- function useGristReady(options) {
1771
- const { isAvailable, docApi, error, reload } = useGristCore(options);
1772
- return { isAvailable, docApi, error, reload };
1773
- }
1774
-
1775
- // src/sdk/mid-level-hooks/use-grist-widget-options-from-context.ts
1776
- import { useCallback as useCallback2, useEffect as useEffect2, useMemo as useMemo3, useRef as useRef2, useState } from "react";
1777
-
1778
- // src/sdk/internal/contexts.tsx
1779
- import { createContext as createContext2, useContext as useContext2, useMemo as useMemo2 } from "react";
1780
-
1781
- // src/sdk/internal/merge-grist-result.ts
1782
- function mergeGristResultFromSlices(slices) {
1783
- const { core, selection, currentTable, writes, reads, widgetOptionsApi, linking, attachmentsRest, theme, sectionApi, suppressAlerts, allowSelectBy } = slices;
1784
- return {
1785
- status: core.status,
1786
- isAvailable: core.isAvailable,
1787
- isReady: core.isReady,
1788
- error: core.error,
1789
- capabilities: core.capabilities,
1790
- record: selection.record,
1791
- records: selection.records,
1792
- mappedRecord: selection.mappedRecord,
1793
- mappings: selection.mappings,
1794
- recordsMappings: selection.recordsMappings,
1795
- columnMappingStatus: selection.columnMappingStatus,
1796
- mode: selection.mode,
1797
- resolveMappedColumnId: selection.resolveMappedColumnId,
1798
- mapBack: selection.mapBack,
1799
- mapBackSkipped: selection.mapBackSkipped,
1800
- isNewRecord: selection.isNewRecord,
1801
- newRecordMappings: selection.newRecordMappings,
1802
- currentTableId: currentTable.currentTableId,
1803
- currentTableLoading: currentTable.currentTableLoading,
1804
- refreshCurrentTable: currentTable.refreshCurrentTable,
1805
- table: writes.table,
1806
- getTable: writes.getTable,
1807
- actionStatus: writes.actionStatus,
1808
- actionError: writes.actionError,
1809
- applyActions: writes.applyActions,
1810
- reload: core.reload,
1811
- fetchTable: reads.fetchTable,
1812
- fetchTableRows: reads.fetchTableRows,
1813
- fetchRow: reads.fetchRow,
1814
- listTables: reads.listTables,
1815
- listColumns: reads.listColumns,
1816
- getDocName: reads.getDocName,
1817
- buildReplicaDocumentFromDocApi: reads.buildReplicaDocumentFromDocApi,
1818
- getAttachmentUrl: attachmentsRest.getAttachmentUrl,
1819
- fetchAttachmentBase64: attachmentsRest.fetchAttachmentBase64,
1820
- fetchAttachmentBlob: attachmentsRest.fetchAttachmentBlob,
1821
- widgetOptions: selection.widgetOptions,
1822
- widgetInteraction: selection.widgetInteraction,
1823
- getWidgetOptions: widgetOptionsApi.getWidgetOptions,
1824
- getWidgetOption: widgetOptionsApi.getWidgetOption,
1825
- setWidgetOption: widgetOptionsApi.setWidgetOption,
1826
- setWidgetOptions: widgetOptionsApi.setWidgetOptions,
1827
- patchWidgetOptions: widgetOptionsApi.patchWidgetOptions,
1828
- clearWidgetOptions: widgetOptionsApi.clearWidgetOptions,
1829
- fetchSelectedTable: reads.fetchSelectedTable,
1830
- fetchSelectedRecord: reads.fetchSelectedRecord,
1831
- readError: reads.readError ?? attachmentsRest.readError,
1832
- setCursorPosition: linking.setCursorPosition,
1833
- setLinkedRowSelection: linking.setLinkedRowSelection,
1834
- getAccessToken: attachmentsRest.getAccessToken,
1835
- fetchWithAuth: attachmentsRest.fetchWithAuth,
1836
- uploadAttachment: attachmentsRest.uploadAttachment,
1837
- theme: theme.theme,
1838
- configure: sectionApi.configure,
1839
- refreshMappings: sectionApi.refreshMappings,
1840
- suppressAlerts,
1841
- allowSelectBy
1842
- };
1843
- }
1844
-
1845
- // src/sdk/internal/contexts.tsx
1846
- var GristCoreContext = createContext2(null);
1847
- var GristSelectionContext = createContext2(null);
1848
- var GristCurrentTableContext = createContext2(null);
1849
- var GristWritesContext = createContext2(null);
1850
- var GristReadsContext = createContext2(null);
1851
- var GristWidgetOptionsApiContext = createContext2(null);
1852
- var GristLinkingContext = createContext2(null);
1853
- var GristAttachmentsRestContext = createContext2(null);
1854
- var GristThemeContext = createContext2(null);
1855
- var GristSectionApiContext = createContext2(null);
1856
- function useRequiredContext(ctx, name) {
1857
- const value = useContext2(ctx);
1858
- if (!value) {
1859
- throw new Error(`${name} must be used inside <GristWidgetProvider>`);
1860
- }
1861
- return value;
1862
- }
1863
- function useGristCoreContext() {
1864
- return useRequiredContext(GristCoreContext, "useGristCoreContext()");
1865
- }
1866
- function useGristSelectionContext() {
1867
- return useRequiredContext(GristSelectionContext, "useGristSelectionContext()");
1868
- }
1869
- function useGristCurrentTableContext() {
1870
- return useRequiredContext(GristCurrentTableContext, "useGristCurrentTableContext()");
1871
- }
1872
- function useGristWritesContext() {
1873
- return useRequiredContext(GristWritesContext, "useGristWritesContext()");
1874
- }
1875
- function useGristReadsContext() {
1876
- return useRequiredContext(GristReadsContext, "useGristReadsContext()");
1877
- }
1878
- function useGristWidgetOptionsApiContext() {
1879
- return useRequiredContext(GristWidgetOptionsApiContext, "useGristWidgetOptionsApiContext()");
1880
- }
1881
- function useGristLinkingContext() {
1882
- return useRequiredContext(GristLinkingContext, "useGristLinkingContext()");
1883
- }
1884
- function useGristAttachmentsRestContext() {
1885
- return useRequiredContext(GristAttachmentsRestContext, "useGristAttachmentsRestContext()");
1886
- }
1887
- function useGristThemeContext() {
1888
- return useRequiredContext(GristThemeContext, "useGristThemeContext()");
1889
- }
1890
- function useGristSectionApiContext() {
1891
- return useRequiredContext(GristSectionApiContext, "useGristSectionApiContext()");
1892
- }
1893
- function useGristFromProvider() {
1894
- const core = useGristCoreContext();
1895
- const selection = useGristSelectionContext();
1896
- const currentTable = useGristCurrentTableContext();
1897
- const writes = useGristWritesContext();
1898
- const reads = useGristReadsContext();
1899
- const widgetOptionsApi = useGristWidgetOptionsApiContext();
1900
- const linking = useGristLinkingContext();
1901
- const attachmentsRest = useGristAttachmentsRestContext();
1902
- const theme = useGristThemeContext();
1903
- const sectionApi = useGristSectionApiContext();
1904
- return useMemo2(
1905
- () => mergeGristResultFromSlices({
1906
- core,
1907
- selection,
1908
- currentTable,
1909
- writes,
1910
- reads,
1911
- widgetOptionsApi,
1912
- linking,
1913
- attachmentsRest,
1914
- theme,
1915
- sectionApi
1916
- }),
1917
- [
1918
- core,
1919
- selection,
1920
- currentTable,
1921
- writes,
1922
- reads,
1923
- widgetOptionsApi,
1924
- linking,
1925
- attachmentsRest,
1926
- theme,
1927
- sectionApi
1928
- ]
1929
- );
1930
- }
1931
-
1932
- // src/sdk/mid-level-hooks/use-grist-widget-options-from-context.ts
1933
- function mergeWithDefaults(defaults, stored, namespace) {
1934
- if (stored === null || stored === void 0) return { ...defaults };
1935
- const source = namespace ? stored[namespace] : stored;
1936
- if (!source || typeof source !== "object") return { ...defaults };
1937
- return { ...defaults, ...source };
1938
- }
1939
- function useGristWidgetOptionsFromContext(config) {
1940
- const debounceMs = config.debounceMs ?? 250;
1941
- const selection = useGristSelectionContext();
1942
- const optionsApi = useGristWidgetOptionsApiContext();
1943
- const defaultsRef = useRef2(config.defaults);
1944
- useEffect2(() => {
1945
- defaultsRef.current = config.defaults;
1946
- }, [config.defaults]);
1947
- const rawOptions = selection.widgetOptions;
1948
- const hasReceived = rawOptions !== null;
1949
- const merged = useMemo3(
1950
- () => mergeWithDefaults(defaultsRef.current, rawOptions, config.namespace),
1951
- [rawOptions, config.namespace]
1952
- );
1953
- const [localOverride, setLocalOverride] = useState(null);
1954
- const options = localOverride ?? merged;
1955
- useEffect2(() => {
1956
- setLocalOverride(null);
1957
- }, [rawOptions]);
1958
- const debounceRef = useRef2(null);
1959
- const flushWrite = useCallback2(
1960
- async (value) => {
1961
- if (config.namespace) {
1962
- await optionsApi.setWidgetOption(config.namespace, value);
1963
- } else {
1964
- await optionsApi.setWidgetOptions({ ...value });
1965
- }
1966
- },
1967
- [config.namespace, optionsApi]
1968
- );
1969
- const scheduleWrite = useCallback2(
1970
- (value) => {
1971
- if (debounceRef.current) window.clearTimeout(debounceRef.current);
1972
- debounceRef.current = window.setTimeout(() => {
1973
- debounceRef.current = null;
1974
- void flushWrite(value);
1975
- }, debounceMs);
1976
- },
1977
- [debounceMs, flushWrite]
1978
- );
1979
- useEffect2(() => {
1980
- return () => {
1981
- if (debounceRef.current) window.clearTimeout(debounceRef.current);
1982
- };
1983
- }, []);
1984
- const setOptions = useCallback2(
1985
- (next) => {
1986
- setLocalOverride(next);
1987
- scheduleWrite(next);
1988
- },
1989
- [scheduleWrite]
1990
- );
1991
- const patchOptions = useCallback2(
1992
- (patch) => {
1993
- setLocalOverride((prev) => {
1994
- const base = prev ?? merged;
1995
- const next = { ...base, ...patch };
1996
- scheduleWrite(next);
1997
- return next;
1998
- });
1999
- },
2000
- [merged, scheduleWrite]
2001
- );
2002
- const reset = useCallback2(async () => {
2003
- if (debounceRef.current) {
2004
- window.clearTimeout(debounceRef.current);
2005
- debounceRef.current = null;
2006
- }
2007
- const next = { ...defaultsRef.current };
2008
- setLocalOverride(null);
2009
- await flushWrite(next);
2010
- }, [flushWrite]);
2011
- return useMemo3(
2012
- () => ({
2013
- options,
2014
- loading: !hasReceived,
2015
- setOptions,
2016
- patchOptions,
2017
- reset
2018
- }),
2019
- [options, hasReceived, setOptions, patchOptions, reset]
2020
- );
2021
- }
2022
-
2023
- // src/sdk/internal/hooks/use-rpc-heartbeat-coalesce.ts
2024
- import { useCallback as useCallback3 } from "react";
2025
- function useRpcHeartbeatCoalesce() {
2026
- const manager = useGristManagerOptional();
2027
- return useCallback3(
2028
- async (fn) => {
2029
- const result = await fn();
2030
- manager?.recordRpcSuccess();
2031
- return result;
2032
- },
2033
- [manager]
2034
- );
2035
- }
2036
-
2037
- export {
2038
- getGristAccessToken,
2039
- fetchWithGristAuth,
2040
- validateColumnMappings,
2041
- initialGristSnapshot,
2042
- deriveStatus,
2043
- deriveErrorMessage,
2044
- deriveCapabilities,
2045
- extractResolvedMappings,
2046
- deriveColumnMappingStatus,
2047
- parseGristWidgetLinkingInfo,
2048
- ensureGristReady,
2049
- resetGristReadySingleton,
2050
- resetGristReadyCacheForTests,
2051
- buildManagerOptionsFromGristOptions,
2052
- recordEvent,
2053
- recordsEvent,
2054
- optionsEvent,
2055
- newRecordEvent,
2056
- resetGristEventsForTests,
2057
- createGristHandshakeManager,
2058
- resetEmbeddedHandshakeManagerForTests,
2059
- GristHandshakeManagerContext,
2060
- useGristManagerOptional,
2061
- useGristManager,
2062
- mergeGristResultFromSlices,
2063
- GristCoreContext,
2064
- GristSelectionContext,
2065
- GristCurrentTableContext,
2066
- GristWritesContext,
2067
- GristReadsContext,
2068
- GristWidgetOptionsApiContext,
2069
- GristLinkingContext,
2070
- GristAttachmentsRestContext,
2071
- GristThemeContext,
2072
- GristSectionApiContext,
2073
- useGristCoreContext,
2074
- useGristSelectionContext,
2075
- useGristCurrentTableContext,
2076
- useGristWritesContext,
2077
- useGristThemeContext,
2078
- useGristFromProvider,
2079
- useGristCore,
2080
- useRpcHeartbeatCoalesce,
2081
- useGristReady,
2082
- useGristWidgetOptionsFromContext
2083
- };
2084
- //# sourceMappingURL=chunk-NO6FYX33.js.map