@softr/sdk 0.0.101-seo.0 → 0.0.102
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/auth/context.d.ts +0 -5
- package/dist/auth/isomorphic.d.ts +1 -2
- package/dist/auth/isomorphic.js +4 -4
- package/dist/auth/session.js +1 -11
- package/dist/cache.js +25 -0
- package/dist/formatting.d.ts +13 -10
- package/dist/formatting.js +11 -6
- package/dist/index.d.ts +3 -2
- package/dist/index.js +3 -2
- package/dist/mcp.d.ts +2 -2
- package/dist/package.js +1 -1
- package/dist/push.d.ts +52 -0
- package/dist/push.js +295 -0
- package/dist/pwa.js +8 -19
- package/dist/route/page.d.ts +3 -41
- package/dist/route/page.js +25 -102
- package/dist/server.d.ts +1 -3
- package/dist/server.js +1 -3
- package/package.json +10 -33
- package/skills/softr-sdk/SKILL.md +7 -8
- package/skills/softr-sdk/ai/SKILL.md +2 -2
- package/skills/softr-sdk/auth/SKILL.md +1 -1
- package/skills/softr-sdk/charts-and-metrics/SKILL.md +1 -1
- package/skills/softr-sdk/current-user/SKILL.md +1 -1
- package/skills/softr-sdk/file-uploads/SKILL.md +1 -1
- package/skills/softr-sdk/formatting/SKILL.md +3 -3
- package/skills/softr-sdk/integrations/SKILL.md +1 -1
- package/skills/softr-sdk/mcp/SKILL.md +1 -1
- package/skills/softr-sdk/push-notifications/SKILL.md +140 -0
- package/skills/softr-sdk/pwa/SKILL.md +1 -1
- package/skills/softr-sdk/record-mutations/SKILL.md +1 -1
- package/skills/softr-sdk/record-queries/SKILL.md +1 -1
- package/skills/softr-sdk/region-visibility/SKILL.md +1 -1
- package/skills/softr-sdk/routes-and-visibility/SKILL.md +4 -90
- package/skills/softr-sdk/workflows/SKILL.md +1 -1
- package/dist/auth/session.d.ts +0 -14
- package/dist/origin.js +0 -16
- package/dist/sitemap.d.ts +0 -35
- package/dist/sitemap.js +0 -56
- package/skills/softr-sdk/sitemap/SKILL.md +0 -112
package/dist/auth/context.d.ts
CHANGED
|
@@ -20,11 +20,6 @@ type Session = {
|
|
|
20
20
|
type SoftrContext = Session & {
|
|
21
21
|
/** Read it with `useFormatting()`. */
|
|
22
22
|
formatting: Formatting;
|
|
23
|
-
/**
|
|
24
|
-
* The app's origin, such as `https://acme.com`, for building absolute URLs.
|
|
25
|
-
* Absent until the root route has resolved `getSoftrContext`.
|
|
26
|
-
*/
|
|
27
|
-
origin?: string;
|
|
28
23
|
};
|
|
29
24
|
//#endregion
|
|
30
25
|
export { SoftrContext };
|
|
@@ -21,13 +21,12 @@ import * as _tanstack_react_start0 from "@tanstack/react-start";
|
|
|
21
21
|
* requestMiddleware: [softrAuthMiddleware()],
|
|
22
22
|
* }))
|
|
23
23
|
*/
|
|
24
|
-
declare function softrAuthMiddleware(): _tanstack_react_start0.RequestMiddlewareAfterServer<{}, readonly [_tanstack_react_start0.RequestMiddlewareAfterServer<{}, undefined, undefined>, _tanstack_react_start0.RequestMiddlewareAfterServer<{}, undefined, undefined>, _tanstack_react_start0.RequestMiddlewareAfterServer<{}, undefined, undefined>, _tanstack_react_start0.RequestMiddlewareAfterServer<{}, undefined, undefined>, _tanstack_react_start0.RequestMiddlewareAfterServer<{}, undefined, undefined>], {
|
|
24
|
+
declare function softrAuthMiddleware(): _tanstack_react_start0.RequestMiddlewareAfterServer<{}, readonly [_tanstack_react_start0.RequestMiddlewareAfterServer<{}, undefined, undefined>, _tanstack_react_start0.RequestMiddlewareAfterServer<{}, undefined, undefined>, _tanstack_react_start0.RequestMiddlewareAfterServer<{}, undefined, undefined>, _tanstack_react_start0.RequestMiddlewareAfterServer<{}, undefined, undefined>, _tanstack_react_start0.RequestMiddlewareAfterServer<{}, undefined, undefined>, _tanstack_react_start0.RequestMiddlewareAfterServer<{}, undefined, undefined>], {
|
|
25
25
|
user: User | null;
|
|
26
26
|
permissions: {
|
|
27
27
|
datasources: {};
|
|
28
28
|
};
|
|
29
29
|
formatting: Formatting;
|
|
30
|
-
origin: string;
|
|
31
30
|
}>;
|
|
32
31
|
/**
|
|
33
32
|
* Resolves the route context of the root route: the visitor and what they may
|
package/dist/auth/isomorphic.js
CHANGED
|
@@ -8,7 +8,7 @@ import { makePlatform } from "./platform.js";
|
|
|
8
8
|
import { settings } from "./methods/settings.js";
|
|
9
9
|
import { bootErrorMiddleware } from "../boot-error.js";
|
|
10
10
|
import { pwaMiddleware } from "../pwa.js";
|
|
11
|
-
import {
|
|
11
|
+
import { pushMiddleware } from "../push.js";
|
|
12
12
|
import { faviconMiddleware } from "../favicon.js";
|
|
13
13
|
import { embeddingMiddleware } from "../embedding.js";
|
|
14
14
|
import { appIdentityMiddleware } from "../app-identity.js";
|
|
@@ -39,8 +39,9 @@ function softrAuthMiddleware() {
|
|
|
39
39
|
appIdentityMiddleware(),
|
|
40
40
|
bootErrorMiddleware(),
|
|
41
41
|
pwaMiddleware(),
|
|
42
|
+
pushMiddleware(),
|
|
42
43
|
faviconMiddleware()
|
|
43
|
-
]).server(async ({ next
|
|
44
|
+
]).server(async ({ next }) => {
|
|
44
45
|
async function getSession() {
|
|
45
46
|
const token = readSessionToken();
|
|
46
47
|
if (token === null) return { user: null };
|
|
@@ -62,8 +63,7 @@ function softrAuthMiddleware() {
|
|
|
62
63
|
return next({ context: {
|
|
63
64
|
user,
|
|
64
65
|
permissions: { datasources: {} },
|
|
65
|
-
formatting: resolveFormatting(settings$1, getRequestHeader("accept-language") ?? null, readUserTimezone())
|
|
66
|
-
origin: appOrigin(request)
|
|
66
|
+
formatting: resolveFormatting(settings$1, getRequestHeader("accept-language") ?? null, readUserTimezone())
|
|
67
67
|
} });
|
|
68
68
|
});
|
|
69
69
|
}
|
package/dist/auth/session.js
CHANGED
|
@@ -45,16 +45,6 @@ function sessionCookie(base) {
|
|
|
45
45
|
function withSessionToken(token, fn) {
|
|
46
46
|
return standInToken.run(token, fn);
|
|
47
47
|
}
|
|
48
|
-
/**
|
|
49
|
-
* Runs `fn` as a signed-out visitor, whoever sent the request, so every `ds`
|
|
50
|
-
* read inside it returns only what a signed-out visitor may see.
|
|
51
|
-
*
|
|
52
|
-
* @example
|
|
53
|
-
* const page = await asSignedOutVisitor(() => ds.list(articlesQuery).limit(100))
|
|
54
|
-
*/
|
|
55
|
-
function asSignedOutVisitor(fn) {
|
|
56
|
-
return standInToken.run(null, async () => await fn());
|
|
57
|
-
}
|
|
58
48
|
/** The platform token this request carries, or `null`. */
|
|
59
49
|
function readSessionToken() {
|
|
60
50
|
const standIn = standInToken.getStore();
|
|
@@ -225,4 +215,4 @@ function openEnvelope(raw, purpose) {
|
|
|
225
215
|
}
|
|
226
216
|
|
|
227
217
|
//#endregion
|
|
228
|
-
export {
|
|
218
|
+
export { clearPendingAuth, clearSession, clearSessionData, makePendingAuthCookie, makeSessionDataCookie, makeSessionTokenCookie, readPendingAuthToken, readSessionData, readSessionToken, withSessionToken };
|
package/dist/cache.js
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { logger } from "./logger.js";
|
|
2
|
+
|
|
3
|
+
//#region src/cache.ts
|
|
4
|
+
/**
|
|
5
|
+
* Reads through a short cache. Never rejects: a failure is logged, reads as
|
|
6
|
+
* `null` and is not remembered, so the next request tries again.
|
|
7
|
+
*/
|
|
8
|
+
function readCached(what, ttlMs, current, store, load) {
|
|
9
|
+
const now = Date.now();
|
|
10
|
+
const cached = current();
|
|
11
|
+
if (cached !== void 0 && cached.expires > now) return cached.value;
|
|
12
|
+
const entry = {
|
|
13
|
+
expires: now + ttlMs,
|
|
14
|
+
value: load().catch((error) => {
|
|
15
|
+
logger.warn(`Could not read ${what}:`, error);
|
|
16
|
+
if (current() === entry) store(void 0);
|
|
17
|
+
return null;
|
|
18
|
+
})
|
|
19
|
+
};
|
|
20
|
+
store(entry);
|
|
21
|
+
return entry.value;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
//#endregion
|
|
25
|
+
export { readCached };
|
package/dist/formatting.d.ts
CHANGED
|
@@ -50,16 +50,18 @@ type DateOptions = {
|
|
|
50
50
|
type DateParts = Pick<Intl.DateTimeFormatOptions, "weekday" | "year" | "month" | "day" | "hour" | "minute" | "timeZoneName">;
|
|
51
51
|
/**
|
|
52
52
|
* The day of a date, in the app's format. A timestamp reads in
|
|
53
|
-
* `formatting.timeZone`, or in UTC while that is unknown. Returns `""` for
|
|
54
|
-
* value that is not a date
|
|
53
|
+
* `formatting.timeZone`, or in UTC while that is unknown. Returns `""` for
|
|
54
|
+
* `null`, `undefined` or a value that is not a date, so a record's nullable
|
|
55
|
+
* date field needs no guard.
|
|
55
56
|
*/
|
|
56
|
-
declare function formatDate(value: DateValue, formatting: Formatting, options?: DateOptions): string;
|
|
57
|
+
declare function formatDate(value: DateValue | null | undefined, formatting: Formatting, options?: DateOptions): string;
|
|
57
58
|
/**
|
|
58
|
-
* The day and the time of a timestamp, in the app's format and zone.
|
|
59
|
-
*
|
|
60
|
-
* visitor's zone
|
|
59
|
+
* The day and the time of a timestamp, in the app's format and zone. Returns
|
|
60
|
+
* `""` for `null`, `undefined` or a value that is not a date. In JSX, prefer
|
|
61
|
+
* `<FormattedDate time />`: on a first visit it waits for the visitor's zone
|
|
62
|
+
* instead of showing UTC.
|
|
61
63
|
*/
|
|
62
|
-
declare function formatDateTime(value: DateValue, formatting: Formatting, options?: DateOptions): string;
|
|
64
|
+
declare function formatDateTime(value: DateValue | null | undefined, formatting: Formatting, options?: DateOptions): string;
|
|
63
65
|
/** A number in the app's number locale. Returns `""` for a value that is not finite. */
|
|
64
66
|
declare function formatNumber(value: number, formatting: Formatting, options?: Intl.NumberFormatOptions): string;
|
|
65
67
|
/**
|
|
@@ -98,7 +100,8 @@ declare function FormattingScope({
|
|
|
98
100
|
/**
|
|
99
101
|
* A date in the app's format, safe to render on the server. A timestamp whose
|
|
100
102
|
* zone is not known yet renders `fallback` until the browser supplies it, so
|
|
101
|
-
* the visitor never sees a UTC time.
|
|
103
|
+
* the visitor never sees a UTC time. A `null` or `undefined` value renders
|
|
104
|
+
* nothing, so a record's nullable date field needs no guard.
|
|
102
105
|
*
|
|
103
106
|
* @example
|
|
104
107
|
* <FormattedDate value={bug.fields.created} />
|
|
@@ -110,11 +113,11 @@ declare function FormattedDate({
|
|
|
110
113
|
fallback,
|
|
111
114
|
...options
|
|
112
115
|
}: DateOptions & {
|
|
113
|
-
value: DateValue;
|
|
116
|
+
value: DateValue | null | undefined;
|
|
114
117
|
/** Shows the time as well as the day. A calendar day such as `2026-10-06` has no time to show. */
|
|
115
118
|
time?: boolean;
|
|
116
119
|
/** What renders while the visitor's zone is unknown. */
|
|
117
120
|
fallback?: ReactNode;
|
|
118
|
-
}): react0.FunctionComponentElement<react0.FragmentProps
|
|
121
|
+
}): react0.FunctionComponentElement<react0.FragmentProps> | null;
|
|
119
122
|
//#endregion
|
|
120
123
|
export { DateOptions, DateParts, DateSeparator, DateValue, FixedDateFormat, FormattedDate, Formatting, FormattingScope, WeekDay, formatDate, formatDateTime, formatNumber, useFormatting };
|
package/dist/formatting.js
CHANGED
|
@@ -88,16 +88,18 @@ function resolveFormatting(settings, acceptLanguage, timeZoneCookie) {
|
|
|
88
88
|
}
|
|
89
89
|
/**
|
|
90
90
|
* The day of a date, in the app's format. A timestamp reads in
|
|
91
|
-
* `formatting.timeZone`, or in UTC while that is unknown. Returns `""` for
|
|
92
|
-
* value that is not a date
|
|
91
|
+
* `formatting.timeZone`, or in UTC while that is unknown. Returns `""` for
|
|
92
|
+
* `null`, `undefined` or a value that is not a date, so a record's nullable
|
|
93
|
+
* date field needs no guard.
|
|
93
94
|
*/
|
|
94
95
|
function formatDate(value, formatting, options = {}) {
|
|
95
96
|
return formatDateValue(value, formatting, false, options);
|
|
96
97
|
}
|
|
97
98
|
/**
|
|
98
|
-
* The day and the time of a timestamp, in the app's format and zone.
|
|
99
|
-
*
|
|
100
|
-
* visitor's zone
|
|
99
|
+
* The day and the time of a timestamp, in the app's format and zone. Returns
|
|
100
|
+
* `""` for `null`, `undefined` or a value that is not a date. In JSX, prefer
|
|
101
|
+
* `<FormattedDate time />`: on a first visit it waits for the visitor's zone
|
|
102
|
+
* instead of showing UTC.
|
|
101
103
|
*/
|
|
102
104
|
function formatDateTime(value, formatting, options = {}) {
|
|
103
105
|
return formatDateValue(value, formatting, true, options);
|
|
@@ -172,7 +174,8 @@ function FormattingScope({ timeZone, locale, children }) {
|
|
|
172
174
|
/**
|
|
173
175
|
* A date in the app's format, safe to render on the server. A timestamp whose
|
|
174
176
|
* zone is not known yet renders `fallback` until the browser supplies it, so
|
|
175
|
-
* the visitor never sees a UTC time.
|
|
177
|
+
* the visitor never sees a UTC time. A `null` or `undefined` value renders
|
|
178
|
+
* nothing, so a record's nullable date field needs no guard.
|
|
176
179
|
*
|
|
177
180
|
* @example
|
|
178
181
|
* <FormattedDate value={bug.fields.created} />
|
|
@@ -180,6 +183,7 @@ function FormattingScope({ timeZone, locale, children }) {
|
|
|
180
183
|
*/
|
|
181
184
|
function FormattedDate({ value, time = false, fallback = null,...options }) {
|
|
182
185
|
const formatting = useFormatting();
|
|
186
|
+
if (value === null || value === void 0) return null;
|
|
183
187
|
if (!isCalendarDay(value) && zoneFor(formatting, options) === null) return createElement(Fragment, null, fallback);
|
|
184
188
|
return createElement(Fragment, null, (time ? formatDateTime : formatDate)(value, formatting, options));
|
|
185
189
|
}
|
|
@@ -192,6 +196,7 @@ function isCalendarDay(value) {
|
|
|
192
196
|
return typeof value === "string" && CALENDAR_DAY.test(value);
|
|
193
197
|
}
|
|
194
198
|
function formatDateValue(value, formatting, withTime, options) {
|
|
199
|
+
if (value === null || value === void 0) return "";
|
|
195
200
|
const day = isCalendarDay(value);
|
|
196
201
|
const date = day ? /* @__PURE__ */ new Date(`${value}T00:00:00Z`) : new Date(value);
|
|
197
202
|
if (Number.isNaN(date.getTime())) return "";
|
package/dist/index.d.ts
CHANGED
|
@@ -7,7 +7,7 @@ import { DateOptions, DateParts, DateSeparator, DateValue, FixedDateFormat, Form
|
|
|
7
7
|
import { SoftrContext } from "./auth/context.js";
|
|
8
8
|
import { AuthSettings } from "./auth/platform.js";
|
|
9
9
|
import { checkAccess, defineVisibility, isAuthorized } from "./route/visibility.js";
|
|
10
|
-
import { Page, PageSettings, definePage,
|
|
10
|
+
import { Page, PageSettings, definePage, pageHead } from "./route/page.js";
|
|
11
11
|
import { assertRouteAccess, guardRoute, isAccessError, isAlreadyAuthenticatedError, isForbiddenError, isUnauthenticatedError } from "./route/route.js";
|
|
12
12
|
import { toReturnPath } from "./auth/returnPath.js";
|
|
13
13
|
import { AuthOptions, AuthSettingsProvider, getAuthSettings, getSoftrContext, initialSoftrContext, softrAuthMiddleware, useAuthSettings, useCurrentUser } from "./auth/isomorphic.js";
|
|
@@ -16,6 +16,7 @@ import { FieldShape, SoftrFieldRegistry, fieldShape, formatDuration, formatField
|
|
|
16
16
|
import { useOverrides } from "./core/use-overrides.js";
|
|
17
17
|
import { useUserTimezone } from "./timezone.js";
|
|
18
18
|
import { PwaInstall, PwaPlatform, SoftrPwaHead, usePwaInstall } from "./pwa.js";
|
|
19
|
+
import { PushNotifications, PushPrompt, usePushNotifications } from "./push.js";
|
|
19
20
|
import { DefaultErrorOverlay } from "./default-error-overlay.js";
|
|
20
21
|
import { Audience } from "./route/audience.js";
|
|
21
|
-
export { type ActionPermissions, type AiAnswer, type AiFile, type AiGenerateInit, type AiMessage, type AiUsage, Audience, type AuthOptions, type AuthSettings, AuthSettingsProvider, type DateOptions, type DateParts, type DateSeparator, type DateValue, DefaultErrorOverlay, type FieldShape, type FileAttachment, type FileItem, type FixedDateFormat, FormattedDate, type Formatting, FormattingScope, type Page, type PageSettings, type PwaInstall, type PwaPlatform, type SoftrContext, type SoftrDatasources, type SoftrFieldRegistry, SoftrPwaHead, type SoftrUserGroupId, type SoftrUserGroups, type SoftrUserProperties, type User, type WeekDay, assertRouteAccess, checkAccess, defineAiAction, defineIntegration, defineMutation, definePage, defineQuery, defineVisibility, defineWorkflow,
|
|
22
|
+
export { type ActionPermissions, type AiAnswer, type AiFile, type AiGenerateInit, type AiMessage, type AiUsage, Audience, type AuthOptions, type AuthSettings, AuthSettingsProvider, type DateOptions, type DateParts, type DateSeparator, type DateValue, DefaultErrorOverlay, type FieldShape, type FileAttachment, type FileItem, type FixedDateFormat, FormattedDate, type Formatting, FormattingScope, type Page, type PageSettings, type PushNotifications, type PushPrompt, type PwaInstall, type PwaPlatform, type SoftrContext, type SoftrDatasources, type SoftrFieldRegistry, SoftrPwaHead, type SoftrUserGroupId, type SoftrUserGroups, type SoftrUserProperties, type User, type WeekDay, assertRouteAccess, checkAccess, defineAiAction, defineIntegration, defineMutation, definePage, defineQuery, defineVisibility, defineWorkflow, fieldShape, formatDate, formatDateTime, formatDuration, formatField, formatNumber, formatValue, getAuthSettings, getSoftrContext, guardRoute, initialSoftrContext, isAccessError, isAlreadyAuthenticatedError, isAuthorized, isForbiddenError, isUnauthenticatedError, pageHead, registerSoftrFields, softrAuthMiddleware, softrMcpMiddleware, toReturnPath, useAuthSettings, useCurrentUser, useFileUpload, useFormatting, useOverrides, usePushNotifications, usePwaInstall, useUserTimezone };
|
package/dist/index.js
CHANGED
|
@@ -2,10 +2,11 @@ import { defineAiAction, defineIntegration, defineMutation, defineQuery, defineW
|
|
|
2
2
|
import { useFileUpload } from "./core/use-file-upload.js";
|
|
3
3
|
import { checkAccess, defineVisibility, isAuthorized } from "./route/visibility.js";
|
|
4
4
|
import { assertRouteAccess, guardRoute, isAccessError, isAlreadyAuthenticatedError, isForbiddenError, isUnauthenticatedError } from "./route/route.js";
|
|
5
|
-
import { definePage,
|
|
5
|
+
import { definePage, pageHead } from "./route/page.js";
|
|
6
6
|
import { toReturnPath } from "./auth/returnPath.js";
|
|
7
7
|
import { FormattedDate, FormattingScope, formatDate, formatDateTime, formatNumber, useFormatting } from "./formatting.js";
|
|
8
8
|
import { SoftrPwaHead, usePwaInstall } from "./pwa.js";
|
|
9
|
+
import { usePushNotifications } from "./push.js";
|
|
9
10
|
import { AuthSettingsProvider, getAuthSettings, getSoftrContext, initialSoftrContext, softrAuthMiddleware, useAuthSettings, useCurrentUser } from "./auth/isomorphic.js";
|
|
10
11
|
import { softrMcpMiddleware } from "./mcp.js";
|
|
11
12
|
import { fieldShape, formatDuration, formatField, formatValue, registerSoftrFields } from "./fields/format.js";
|
|
@@ -14,4 +15,4 @@ import { useUserTimezone } from "./timezone.js";
|
|
|
14
15
|
import { DefaultErrorOverlay } from "./default-error-overlay.js";
|
|
15
16
|
import { Audience } from "./route/audience.js";
|
|
16
17
|
|
|
17
|
-
export { Audience, AuthSettingsProvider, DefaultErrorOverlay, FormattedDate, FormattingScope, SoftrPwaHead, assertRouteAccess, checkAccess, defineAiAction, defineIntegration, defineMutation, definePage, defineQuery, defineVisibility, defineWorkflow,
|
|
18
|
+
export { Audience, AuthSettingsProvider, DefaultErrorOverlay, FormattedDate, FormattingScope, SoftrPwaHead, assertRouteAccess, checkAccess, defineAiAction, defineIntegration, defineMutation, definePage, defineQuery, defineVisibility, defineWorkflow, fieldShape, formatDate, formatDateTime, formatDuration, formatField, formatNumber, formatValue, getAuthSettings, getSoftrContext, guardRoute, initialSoftrContext, isAccessError, isAlreadyAuthenticatedError, isAuthorized, isForbiddenError, isUnauthenticatedError, pageHead, registerSoftrFields, softrAuthMiddleware, softrMcpMiddleware, toReturnPath, useAuthSettings, useCurrentUser, useFileUpload, useFormatting, useOverrides, usePushNotifications, usePwaInstall, useUserTimezone };
|
package/dist/mcp.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { DatasourceAction } from "./action.js";
|
|
2
|
-
import * as
|
|
2
|
+
import * as _tanstack_react_start8 from "@tanstack/react-start";
|
|
3
3
|
|
|
4
4
|
//#region src/mcp.d.ts
|
|
5
5
|
|
|
@@ -31,6 +31,6 @@ type SoftrMcpOptions = {
|
|
|
31
31
|
* ],
|
|
32
32
|
* }))
|
|
33
33
|
*/
|
|
34
|
-
declare function softrMcpMiddleware(options?: SoftrMcpOptions):
|
|
34
|
+
declare function softrMcpMiddleware(options?: SoftrMcpOptions): _tanstack_react_start8.RequestMiddlewareAfterServer<{}, undefined, undefined>;
|
|
35
35
|
//#endregion
|
|
36
36
|
export { softrMcpMiddleware };
|
package/dist/package.js
CHANGED
package/dist/push.d.ts
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import "@tanstack/react-start";
|
|
2
|
+
|
|
3
|
+
//#region src/push.d.ts
|
|
4
|
+
|
|
5
|
+
/** What the builder wrote in Studio for the prompt. Any of it may be missing. */
|
|
6
|
+
type PushPrompt = {
|
|
7
|
+
title: string | null;
|
|
8
|
+
message: string | null;
|
|
9
|
+
enableButtonLabel: string | null;
|
|
10
|
+
};
|
|
11
|
+
type PushNotifications = /** Loading, signed out, push off for this app or device, or a browser without push. */
|
|
12
|
+
{
|
|
13
|
+
status: "unavailable";
|
|
14
|
+
}
|
|
15
|
+
/** iPhone and iPad offer push only inside the installed app. */ | {
|
|
16
|
+
status: "install-first";
|
|
17
|
+
prompt: PushPrompt;
|
|
18
|
+
} | {
|
|
19
|
+
status: "ask";
|
|
20
|
+
prompt: PushPrompt;
|
|
21
|
+
/** The visitor skipped the prompt recently, within the builder's skip days. Hide the prompt. */
|
|
22
|
+
dismissed: boolean;
|
|
23
|
+
/** Asks the browser for permission and subscribes. Call it from a click. */
|
|
24
|
+
subscribe: () => Promise<void>;
|
|
25
|
+
/** Hides the prompt for as long as the builder set in Studio. */
|
|
26
|
+
dismiss: () => void;
|
|
27
|
+
} | {
|
|
28
|
+
status: "subscribed";
|
|
29
|
+
unsubscribe: () => Promise<void>;
|
|
30
|
+
}
|
|
31
|
+
/** The visitor blocked notifications in the browser. Only they can undo it, in the browser's settings. */ | {
|
|
32
|
+
status: "blocked";
|
|
33
|
+
};
|
|
34
|
+
/**
|
|
35
|
+
* Push notifications for the signed-in visitor. Call it once, in the one
|
|
36
|
+
* component that shows the prompt, rendered once in the root route's
|
|
37
|
+
* `RootDocument`, so this browser stays registered. Each call keeps state of
|
|
38
|
+
* its own, so a second call does not see a subscribe made through the first.
|
|
39
|
+
* Show a prompt only while `status` is `ask`
|
|
40
|
+
* and the prompt is not `dismissed`.
|
|
41
|
+
*
|
|
42
|
+
* @example
|
|
43
|
+
* function EnableNotifications() {
|
|
44
|
+
* const push = usePushNotifications()
|
|
45
|
+
* if (push.status !== "ask" || push.dismissed) return null
|
|
46
|
+
* const turnOn = () => push.subscribe().catch(() => toast.error("Notifications could not be turned on."))
|
|
47
|
+
* return <button onClick={turnOn}>{push.prompt.enableButtonLabel ?? "Turn on"}</button>
|
|
48
|
+
* }
|
|
49
|
+
*/
|
|
50
|
+
declare function usePushNotifications(): PushNotifications;
|
|
51
|
+
//#endregion
|
|
52
|
+
export { PushNotifications, PushPrompt, usePushNotifications };
|
package/dist/push.js
ADDED
|
@@ -0,0 +1,295 @@
|
|
|
1
|
+
import { softrApiUrl } from "./softr-api.js";
|
|
2
|
+
import { fetch } from "./fetch.js";
|
|
3
|
+
import { sessionConfig } from "./auth/config.js";
|
|
4
|
+
import { readSessionToken } from "./auth/session.js";
|
|
5
|
+
import { readCached } from "./cache.js";
|
|
6
|
+
import { detectPlatform, isStandalone } from "./pwa.js";
|
|
7
|
+
import { z } from "zod";
|
|
8
|
+
import { useCallback, useEffect, useState } from "react";
|
|
9
|
+
import { createMiddleware } from "@tanstack/react-start";
|
|
10
|
+
import { rootRouteId, useRouteContext } from "@tanstack/react-router";
|
|
11
|
+
|
|
12
|
+
//#region src/push.ts
|
|
13
|
+
const WORKER_PATH = "/_softr/sw.js";
|
|
14
|
+
const SETTINGS_PATH = "/_softr/push.json";
|
|
15
|
+
const SUBSCRIPTION_PATH = "/_softr/push";
|
|
16
|
+
const TTL_MS = 6e4;
|
|
17
|
+
const promptSchema = z.object({
|
|
18
|
+
title: z.string().nullable(),
|
|
19
|
+
message: z.string().nullable(),
|
|
20
|
+
enableButtonLabel: z.string().nullable(),
|
|
21
|
+
skipDays: z.number().nullable()
|
|
22
|
+
});
|
|
23
|
+
const settingsSchema = z.object({
|
|
24
|
+
vapidPublicKey: z.string(),
|
|
25
|
+
desktopEnabled: z.boolean(),
|
|
26
|
+
mobileEnabled: z.boolean(),
|
|
27
|
+
permissionPrompt: promptSchema.nullable()
|
|
28
|
+
});
|
|
29
|
+
const browserSubscriptionSchema = z.object({
|
|
30
|
+
endpoint: z.string(),
|
|
31
|
+
keys: z.object({
|
|
32
|
+
p256dh: z.string(),
|
|
33
|
+
auth: z.string()
|
|
34
|
+
})
|
|
35
|
+
});
|
|
36
|
+
let cachedSettings;
|
|
37
|
+
let cachedWorker;
|
|
38
|
+
function platformPushUrl() {
|
|
39
|
+
const { applicationId } = sessionConfig();
|
|
40
|
+
return `${softrApiUrl("SOFTR_PLATFORM_API_URL")}/v1/vibe/applications/${applicationId}/push`;
|
|
41
|
+
}
|
|
42
|
+
function readSettings() {
|
|
43
|
+
return readCached("push notifications from Softr", TTL_MS, () => cachedSettings, (entry) => cachedSettings = entry, async () => {
|
|
44
|
+
const response = await fetch(platformPushUrl(), { headers: { accept: "application/json" } });
|
|
45
|
+
if (response.status === 404) return null;
|
|
46
|
+
if (!response.ok) throw new Error(`The platform answered ${response.status}`);
|
|
47
|
+
return settingsSchema.parse(await response.json());
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
function readWorker() {
|
|
51
|
+
return readCached("the push service worker from Softr", TTL_MS, () => cachedWorker, (entry) => cachedWorker = entry, async () => {
|
|
52
|
+
const response = await fetch(`${softrApiUrl("SOFTR_PLATFORM_API_URL")}/pwa/sw.js`);
|
|
53
|
+
if (!response.ok) throw new Error(`The platform answered ${response.status}`);
|
|
54
|
+
return response.text();
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Serves push notifications from the app's own origin: the service worker, the
|
|
59
|
+
* app's push settings, and saving or removing this browser's subscription for
|
|
60
|
+
* the signed-in visitor. Every other request passes through untouched.
|
|
61
|
+
*/
|
|
62
|
+
function pushMiddleware() {
|
|
63
|
+
return createMiddleware({ type: "request" }).server(async ({ next, pathname, request }) => {
|
|
64
|
+
if (pathname === WORKER_PATH && request.method === "GET") {
|
|
65
|
+
const worker = await readWorker();
|
|
66
|
+
if (worker === null) return new Response(null, {
|
|
67
|
+
status: 503,
|
|
68
|
+
headers: { "cache-control": "no-store" }
|
|
69
|
+
});
|
|
70
|
+
return new Response(worker, { headers: {
|
|
71
|
+
"content-type": "text/javascript; charset=utf-8",
|
|
72
|
+
"cache-control": "no-cache",
|
|
73
|
+
"service-worker-allowed": "/"
|
|
74
|
+
} });
|
|
75
|
+
}
|
|
76
|
+
if (pathname === SETTINGS_PATH && request.method === "GET") {
|
|
77
|
+
const settings = await readSettings();
|
|
78
|
+
if (settings === null) return new Response(null, { status: 404 });
|
|
79
|
+
return Response.json(settings, { headers: { "cache-control": "no-store" } });
|
|
80
|
+
}
|
|
81
|
+
if (pathname === SUBSCRIPTION_PATH && (request.method === "POST" || request.method === "DELETE")) {
|
|
82
|
+
if (!request.headers.get("content-type")?.startsWith("application/json")) return new Response(null, { status: 415 });
|
|
83
|
+
const token = readSessionToken();
|
|
84
|
+
if (token === null) return new Response(null, { status: 401 });
|
|
85
|
+
const body = z.object({ subscription: browserSubscriptionSchema }).safeParse(await request.json().catch(() => null));
|
|
86
|
+
if (!body.success) return new Response(null, { status: 400 });
|
|
87
|
+
const response = await (request.method === "POST" ? fetch(platformPushUrl(), {
|
|
88
|
+
method: "POST",
|
|
89
|
+
headers: {
|
|
90
|
+
"content-type": "application/json",
|
|
91
|
+
authorization: `Bearer ${token}`
|
|
92
|
+
},
|
|
93
|
+
body: JSON.stringify({
|
|
94
|
+
origin: new URL(request.url).origin,
|
|
95
|
+
userAgent: request.headers.get("user-agent"),
|
|
96
|
+
subscription: body.data.subscription
|
|
97
|
+
})
|
|
98
|
+
}) : fetch(`${platformPushUrl()}?${new URLSearchParams({ endpoint: body.data.subscription.endpoint })}`, {
|
|
99
|
+
method: "DELETE",
|
|
100
|
+
headers: { authorization: `Bearer ${token}` }
|
|
101
|
+
})).catch(() => null);
|
|
102
|
+
if (response === null) return new Response(null, { status: 502 });
|
|
103
|
+
return new Response(null, { status: response.ok ? 204 : response.status });
|
|
104
|
+
}
|
|
105
|
+
return next();
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
const DISMISSED_AT_KEY = "softr-push-dismissed-at";
|
|
109
|
+
/**
|
|
110
|
+
* Push notifications for the signed-in visitor. Call it once, in the one
|
|
111
|
+
* component that shows the prompt, rendered once in the root route's
|
|
112
|
+
* `RootDocument`, so this browser stays registered. Each call keeps state of
|
|
113
|
+
* its own, so a second call does not see a subscribe made through the first.
|
|
114
|
+
* Show a prompt only while `status` is `ask`
|
|
115
|
+
* and the prompt is not `dismissed`.
|
|
116
|
+
*
|
|
117
|
+
* @example
|
|
118
|
+
* function EnableNotifications() {
|
|
119
|
+
* const push = usePushNotifications()
|
|
120
|
+
* if (push.status !== "ask" || push.dismissed) return null
|
|
121
|
+
* const turnOn = () => push.subscribe().catch(() => toast.error("Notifications could not be turned on."))
|
|
122
|
+
* return <button onClick={turnOn}>{push.prompt.enableButtonLabel ?? "Turn on"}</button>
|
|
123
|
+
* }
|
|
124
|
+
*/
|
|
125
|
+
function usePushNotifications() {
|
|
126
|
+
const signedIn = useRouteContext({
|
|
127
|
+
from: rootRouteId,
|
|
128
|
+
select: (context) => context.user !== null
|
|
129
|
+
});
|
|
130
|
+
const [settings, setSettings] = useState(null);
|
|
131
|
+
const [registration, setRegistration] = useState(null);
|
|
132
|
+
const [subscribed, setSubscribed] = useState(false);
|
|
133
|
+
const [permission, setPermission] = useState("default");
|
|
134
|
+
const [dismissedAt, setDismissedAt] = useState(null);
|
|
135
|
+
useEffect(() => {
|
|
136
|
+
if (process.env.NODE_ENV !== "production" || !("serviceWorker" in navigator)) return;
|
|
137
|
+
if (!signedIn) {
|
|
138
|
+
try {
|
|
139
|
+
localStorage.removeItem(DISMISSED_AT_KEY);
|
|
140
|
+
} catch {}
|
|
141
|
+
setDismissedAt(null);
|
|
142
|
+
setSettings(null);
|
|
143
|
+
setSubscribed(false);
|
|
144
|
+
return;
|
|
145
|
+
}
|
|
146
|
+
let cancelled = false;
|
|
147
|
+
(async () => {
|
|
148
|
+
const response = await globalThis.fetch(SETTINGS_PATH, { headers: { accept: "application/json" } });
|
|
149
|
+
if (!response.ok) return;
|
|
150
|
+
const parsed = settingsSchema.safeParse(await response.json());
|
|
151
|
+
if (!parsed.success || cancelled) return;
|
|
152
|
+
setDismissedAt(readDismissedAt());
|
|
153
|
+
setSettings(parsed.data);
|
|
154
|
+
if (!("PushManager" in window) || !("Notification" in window)) return;
|
|
155
|
+
setPermission(Notification.permission);
|
|
156
|
+
const registered = await navigator.serviceWorker.register(WORKER_PATH, { scope: "/" });
|
|
157
|
+
if (cancelled) return;
|
|
158
|
+
if (Notification.permission !== "granted") {
|
|
159
|
+
setRegistration(registered);
|
|
160
|
+
return;
|
|
161
|
+
}
|
|
162
|
+
const subscription = await registered.pushManager.getSubscription() ?? await registered.pushManager.subscribe({
|
|
163
|
+
userVisibleOnly: true,
|
|
164
|
+
applicationServerKey: decodeBase64Url(parsed.data.vapidPublicKey)
|
|
165
|
+
});
|
|
166
|
+
if (cancelled) return;
|
|
167
|
+
setSubscribed(await sendSubscription("POST", subscription));
|
|
168
|
+
setRegistration(registered);
|
|
169
|
+
})().catch((error) => console.warn("[@softr/sdk] Could not set up push notifications:", error));
|
|
170
|
+
return () => {
|
|
171
|
+
cancelled = true;
|
|
172
|
+
};
|
|
173
|
+
}, [signedIn]);
|
|
174
|
+
useEffect(() => {
|
|
175
|
+
if (registration === null) return;
|
|
176
|
+
return listenToWorker();
|
|
177
|
+
}, [registration]);
|
|
178
|
+
const subscribe = useCallback(async () => {
|
|
179
|
+
if (registration === null || settings === null) return;
|
|
180
|
+
const granted = await Notification.requestPermission();
|
|
181
|
+
setPermission(granted);
|
|
182
|
+
if (granted !== "granted") return;
|
|
183
|
+
const subscription = await registration.pushManager.subscribe({
|
|
184
|
+
userVisibleOnly: true,
|
|
185
|
+
applicationServerKey: decodeBase64Url(settings.vapidPublicKey)
|
|
186
|
+
});
|
|
187
|
+
if (!await sendSubscription("POST", subscription)) {
|
|
188
|
+
await subscription.unsubscribe();
|
|
189
|
+
throw new Error("Could not turn on push notifications");
|
|
190
|
+
}
|
|
191
|
+
setSubscribed(true);
|
|
192
|
+
}, [registration, settings]);
|
|
193
|
+
const unsubscribe = useCallback(async () => {
|
|
194
|
+
const subscription = await registration?.pushManager.getSubscription();
|
|
195
|
+
if (!subscription) return;
|
|
196
|
+
await sendSubscription("DELETE", subscription);
|
|
197
|
+
await subscription.unsubscribe();
|
|
198
|
+
setSubscribed(false);
|
|
199
|
+
}, [registration]);
|
|
200
|
+
const dismiss = useCallback(() => {
|
|
201
|
+
const now = Date.now();
|
|
202
|
+
try {
|
|
203
|
+
localStorage.setItem(DISMISSED_AT_KEY, String(now));
|
|
204
|
+
} catch {}
|
|
205
|
+
setDismissedAt(now);
|
|
206
|
+
}, []);
|
|
207
|
+
if (settings === null) return { status: "unavailable" };
|
|
208
|
+
const platform = detectPlatform();
|
|
209
|
+
if (platform !== "desktop" ? !settings.mobileEnabled : !settings.desktopEnabled) return { status: "unavailable" };
|
|
210
|
+
const prompt = {
|
|
211
|
+
title: settings.permissionPrompt?.title ?? null,
|
|
212
|
+
message: settings.permissionPrompt?.message ?? null,
|
|
213
|
+
enableButtonLabel: settings.permissionPrompt?.enableButtonLabel ?? null
|
|
214
|
+
};
|
|
215
|
+
if (platform === "ios" && !isStandalone()) return {
|
|
216
|
+
status: "install-first",
|
|
217
|
+
prompt
|
|
218
|
+
};
|
|
219
|
+
if (registration === null) return { status: "unavailable" };
|
|
220
|
+
if (subscribed) return {
|
|
221
|
+
status: "subscribed",
|
|
222
|
+
unsubscribe
|
|
223
|
+
};
|
|
224
|
+
if (permission === "denied") return { status: "blocked" };
|
|
225
|
+
return {
|
|
226
|
+
status: "ask",
|
|
227
|
+
prompt,
|
|
228
|
+
dismissed: isDismissed(dismissedAt, settings.permissionPrompt?.skipDays ?? null),
|
|
229
|
+
subscribe,
|
|
230
|
+
dismiss
|
|
231
|
+
};
|
|
232
|
+
}
|
|
233
|
+
async function sendSubscription(method, subscription) {
|
|
234
|
+
return (await globalThis.fetch(SUBSCRIPTION_PATH, {
|
|
235
|
+
method,
|
|
236
|
+
headers: { "content-type": "application/json" },
|
|
237
|
+
body: JSON.stringify({ subscription: subscription.toJSON() })
|
|
238
|
+
})).ok;
|
|
239
|
+
}
|
|
240
|
+
/** A missing skip-days setting means a skipped prompt never comes back on its own. */
|
|
241
|
+
function isDismissed(dismissedAt, skipDays) {
|
|
242
|
+
if (dismissedAt === null) return false;
|
|
243
|
+
if (skipDays === null) return true;
|
|
244
|
+
return Date.now() - dismissedAt < Math.max(skipDays, 1) * 24 * 60 * 60 * 1e3;
|
|
245
|
+
}
|
|
246
|
+
function readDismissedAt() {
|
|
247
|
+
try {
|
|
248
|
+
const stored = Number(localStorage.getItem(DISMISSED_AT_KEY));
|
|
249
|
+
return Number.isFinite(stored) && stored > 0 ? stored : null;
|
|
250
|
+
} catch {
|
|
251
|
+
return null;
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
/**
|
|
255
|
+
* Answers the service worker, which routes a notification click to the
|
|
256
|
+
* installed app when it is open, and keeps the app icon's badge right.
|
|
257
|
+
*/
|
|
258
|
+
function listenToWorker() {
|
|
259
|
+
const worker = navigator.serviceWorker;
|
|
260
|
+
const standalone = isStandalone();
|
|
261
|
+
if (standalone) worker.controller?.postMessage({ type: "pwa-standalone-opened" });
|
|
262
|
+
const onMessage = (event) => {
|
|
263
|
+
if (event.data === "is-this-standalone") {
|
|
264
|
+
event.ports[0]?.postMessage(standalone ? "yes" : "no");
|
|
265
|
+
return;
|
|
266
|
+
}
|
|
267
|
+
if (event.data?.type === "softr-pwa-redirect" && typeof event.data.url === "string") {
|
|
268
|
+
const target = new URL(event.data.url, window.location.href);
|
|
269
|
+
if (target.origin === window.location.origin) window.location.assign(target.href);
|
|
270
|
+
}
|
|
271
|
+
};
|
|
272
|
+
const onVisible = () => {
|
|
273
|
+
if (document.visibilityState === "visible") worker.controller?.postMessage("reset-badge-count");
|
|
274
|
+
};
|
|
275
|
+
const onInstallOffered = () => worker.controller?.postMessage({ type: "pwa-uninstalled" });
|
|
276
|
+
worker.addEventListener("message", onMessage);
|
|
277
|
+
document.addEventListener("visibilitychange", onVisible);
|
|
278
|
+
window.addEventListener("beforeinstallprompt", onInstallOffered);
|
|
279
|
+
onVisible();
|
|
280
|
+
return () => {
|
|
281
|
+
worker.removeEventListener("message", onMessage);
|
|
282
|
+
document.removeEventListener("visibilitychange", onVisible);
|
|
283
|
+
window.removeEventListener("beforeinstallprompt", onInstallOffered);
|
|
284
|
+
};
|
|
285
|
+
}
|
|
286
|
+
function decodeBase64Url(value) {
|
|
287
|
+
const base64 = value.replace(/-/g, "+").replace(/_/g, "/").padEnd(Math.ceil(value.length / 4) * 4, "=");
|
|
288
|
+
const binary = atob(base64);
|
|
289
|
+
const bytes = new Uint8Array(binary.length);
|
|
290
|
+
for (let index = 0; index < binary.length; index++) bytes[index] = binary.charCodeAt(index);
|
|
291
|
+
return bytes;
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
//#endregion
|
|
295
|
+
export { pushMiddleware, usePushNotifications };
|