@plitzi/sdk-server 0.39.0 → 0.39.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +22 -0
- package/README.md +364 -61
- package/dist/adapters/authAdapters.d.ts +2 -1
- package/dist/adapters/cloudAdapters.d.ts +2 -1
- package/dist/adapters/jsonAdapters.d.ts +2 -1
- package/dist/adapters/space/index.d.ts +3 -3
- package/dist/adapters/space/resolvers.d.ts +41 -4
- package/dist/adapters/space/types.d.ts +11 -1
- package/dist/auth.d.ts +9 -29
- package/dist/auth.js +2323 -22
- package/dist/bundle.d.ts +6 -0
- package/dist/bundle.js +171 -0
- package/dist/cache.d.ts +7 -0
- package/dist/cache.js +1 -0
- package/dist/chunks/buildBody-W9D8ySNY.js +1450 -0
- package/dist/chunks/core-TlrWmT4B.js +2118 -0
- package/dist/chunks/createServer-Bd_b7T3k.js +2956 -0
- package/dist/chunks/platform-DhdFYWm5.js +38 -0
- package/dist/{core/auth/routes.js → chunks/renewal-D98v6-Jd.js} +23 -4
- package/dist/chunks/template-M3IEZ6os.js +42 -0
- package/dist/{core/auth/throttle.js → chunks/throttle-BH7JLIOF.js} +4 -5
- package/dist/chunks/token-B2uY9JzU.js +824 -0
- package/dist/chunks/views/inline/keepTaps.js +1 -0
- package/dist/chunks/views/inline/motionSeen.js +2 -0
- package/dist/{modules/ssr → chunks}/views/template.ejs +62 -100
- package/dist/core/auth/api/admin.d.ts +2 -3
- package/dist/core/auth/api/context.d.ts +24 -29
- package/dist/core/auth/api/factors.d.ts +1 -2
- package/dist/core/auth/api/index.d.ts +30 -30
- package/dist/core/auth/api/profile.d.ts +1 -1
- package/dist/core/auth/api/session.d.ts +1 -2
- package/dist/core/auth/api/types.d.ts +2 -280
- package/dist/core/auth/api/values.d.ts +2 -3
- package/dist/core/auth/createAuth.d.ts +67 -76
- package/dist/core/auth/oauth/index.d.ts +1 -1
- package/dist/core/auth/oauth/providers/oidc.d.ts +0 -6
- package/dist/core/auth/renewal.d.ts +1 -3
- package/dist/core/auth/routes.d.ts +1 -5
- package/dist/core/auth/throttle.d.ts +2 -2
- package/dist/core/createServer.d.ts +14 -5
- package/dist/core/handlers/authMiddleware.d.ts +1 -2
- package/dist/core/handlers/authRouteHandlers.d.ts +1 -2
- package/dist/core/handlers/csrfMiddleware.d.ts +1 -2
- package/dist/core/handlers/oauthRouteHandlers.d.ts +1 -1
- package/dist/core/handlers/socialRouteHandlers.d.ts +2 -3
- package/dist/core/handlers/types.d.ts +1 -3
- package/dist/core/http/pageContext.d.ts +25 -0
- package/dist/core/http/stages/authApi.d.ts +1 -1
- package/dist/core/http/stages/authRoutes.d.ts +4 -10
- package/dist/core/http/stages/cspReport.d.ts +6 -0
- package/dist/core/http/stages/defaultFavicon.d.ts +3 -0
- package/dist/core/http/stages/exchangeRoute.d.ts +3 -2
- package/dist/core/http/stages/fontAssets.d.ts +3 -2
- package/dist/core/http/stages/googleFonts.d.ts +7 -0
- package/dist/core/http/stages/images.d.ts +4 -3
- package/dist/core/http/stages/livePages.d.ts +3 -2
- package/dist/core/http/stages/oauth.d.ts +2 -2
- package/dist/core/http/stages/pluginAssets.d.ts +2 -1
- package/dist/core/http/stages/{static.d.ts → sdkAssets.d.ts} +1 -4
- package/dist/core/http/stages/sessionRenewal.d.ts +4 -3
- package/dist/core/http/stages/signInRoute.d.ts +3 -2
- package/dist/core/oauth/authorize.d.ts +1 -1
- package/dist/core/oauth/challenge.d.ts +1 -1
- package/dist/core/oauth/consentPage.d.ts +1 -1
- package/dist/core/oauth/issueContext.d.ts +1 -1
- package/dist/core/oauth/metadata.d.ts +1 -5
- package/dist/core/oauth/records.d.ts +1 -1
- package/dist/core/oauth/register.d.ts +1 -1
- package/dist/core/oauth/respond.d.ts +1 -1
- package/dist/core/oauth/token.d.ts +1 -1
- package/dist/core/platform.d.ts +13 -0
- package/dist/core/sdkAssets.d.ts +11 -1
- package/dist/core/server/pageServer.d.ts +4 -3
- package/dist/core/server/{fleet/relay.d.ts → relay.d.ts} +1 -2
- package/dist/core/server/reportCacheSharing.d.ts +11 -0
- package/dist/core/services/registry.d.ts +4 -2
- package/dist/core/services/resolve.d.ts +1 -9
- package/dist/core/services/robotsTxt.d.ts +2 -1
- package/dist/core/services/rsc.d.ts +2 -1
- package/dist/core/services/servedSpace.d.ts +1 -1
- package/dist/core/services/sitemapXml.d.ts +2 -1
- package/dist/core/services/spaceDocument.d.ts +2 -1
- package/dist/core/services/ssr.d.ts +2 -1
- package/dist/core/services/styleSheet.d.ts +3 -0
- package/dist/env.js +1 -2
- package/dist/handlers.d.ts +1 -1
- package/dist/handlers.js +517 -5
- package/dist/helpers/buildServerInfo.d.ts +3 -1
- package/dist/helpers/cache/cacheManager.d.ts +1 -1
- package/dist/helpers/cache/defaults.d.ts +22 -1
- package/dist/helpers/cache/index.d.ts +11 -4
- package/dist/helpers/cache/keys.d.ts +27 -4
- package/dist/helpers/cache/limits.d.ts +16 -0
- package/dist/helpers/cache/pages.d.ts +20 -0
- package/dist/helpers/cache/queryParams.d.ts +11 -0
- package/dist/helpers/cache/serverCaches.d.ts +24 -11
- package/dist/helpers/cache/sharedCache.d.ts +29 -0
- package/dist/helpers/hydrationPayload.d.ts +35 -8
- package/dist/helpers/metrics.d.ts +5 -1
- package/dist/helpers/paintedCookie.d.ts +13 -0
- package/dist/helpers/visitorScheme.d.ts +10 -0
- package/dist/hosts/authoringHost/index.d.ts +1 -1
- package/dist/hosts/project/agentRuns.d.ts +1 -1
- package/dist/hosts/project/bundle.d.ts +22 -0
- package/dist/hosts/project/laterAsks.d.ts +1 -1
- package/dist/hosts/project/plugins.d.ts +3 -2
- package/dist/hosts/project/serveProject.d.ts +17 -7
- package/dist/hosts/project/spaceFailure.d.ts +1 -1
- package/dist/index.d.ts +9 -18
- package/dist/index.js +168 -24
- package/dist/modules/fonts/googleFonts.d.ts +27 -0
- package/dist/modules/images/imageProxy.d.ts +1 -1
- package/dist/modules/rsc/connectorRscData.d.ts +10 -12
- package/dist/modules/rsc/externalQueryReader.d.ts +28 -5
- package/dist/modules/rsc/handler.d.ts +3 -1
- package/dist/modules/rsc/matchRscPage.d.ts +0 -8
- package/dist/modules/rsc/publicFileResolver.d.ts +1 -1
- package/dist/modules/rsc/resolveRscData.d.ts +3 -31
- package/dist/modules/ssr/Component.d.ts +6 -3
- package/dist/modules/ssr/applySSRResult.d.ts +2 -6
- package/dist/modules/ssr/buildBody.d.ts +7 -2
- package/dist/modules/ssr/defaultFavicon.d.ts +10 -0
- package/dist/modules/ssr/earlyHints.d.ts +18 -0
- package/dist/modules/ssr/handler.d.ts +4 -2
- package/dist/modules/ssr/loadPluginComponents.d.ts +2 -1
- package/dist/modules/ssr/meterPage.d.ts +4 -0
- package/dist/modules/ssr/pageCache.d.ts +47 -0
- package/dist/modules/ssr/prepareRender.d.ts +11 -3
- package/dist/modules/ssr/preview.d.ts +5 -3
- package/dist/modules/ssr/redisPageStore.d.ts +29 -0
- package/dist/modules/ssr/registerExternalPlugins.d.ts +1 -1
- package/dist/modules/ssr/renderTurns.d.ts +34 -0
- package/dist/modules/ssr/reportMissingPlugins.d.ts +0 -7
- package/dist/modules/ssr/scriptPolicy.d.ts +39 -0
- package/dist/modules/ssr/spaceDocument.d.ts +25 -2
- package/dist/modules/ssr/streamBody.d.ts +9 -3
- package/dist/modules/ssr/styleSheet.d.ts +15 -0
- package/dist/modules/ssr/template.d.ts +8 -1
- package/dist/oauth.js +139 -9
- package/dist/platform.d.ts +6 -0
- package/dist/platform.js +1 -0
- package/dist/project.js +939 -1
- package/dist/spaces.d.ts +7 -0
- package/dist/spaces.js +1 -0
- package/dist/ssr.d.ts +1 -2
- package/dist/ssr.js +1 -4
- package/dist/types/config.d.ts +252 -0
- package/dist/types/index.d.ts +2 -0
- package/dist/types/server.d.ts +111 -0
- package/package.json +41 -83
- package/skills/plitzi-authoring/recipes/server-data.ts +4 -0
- package/skills/plitzi-authoring/reference/accessibility.md +9 -2
- package/skills/plitzi-authoring/reference/auth.md +6 -1
- package/skills/plitzi-authoring/reference/authoring-errors.md +7 -4
- package/skills/plitzi-authoring/reference/flows.md +9 -9
- package/skills/plitzi-authoring/reference/kept-state.md +12 -0
- package/skills/plitzi-authoring/reference/lists.md +7 -1
- package/skills/plitzi-authoring/reference/plugins.md +5 -2
- package/skills/plitzi-authoring/reference/testing.md +3 -3
- package/dist/actions.d.ts +0 -87
- package/dist/actions.js +0 -23
- package/dist/adapters/authAdapters.js +0 -12
- package/dist/adapters/cloudAdapters.js +0 -364
- package/dist/adapters/jsonAdapters.js +0 -88
- package/dist/adapters/space/index.js +0 -122
- package/dist/adapters/space/resolvers.js +0 -79
- package/dist/adapters/space/types.js +0 -41
- package/dist/core/auth/api/accounts.js +0 -175
- package/dist/core/auth/api/admin.js +0 -146
- package/dist/core/auth/api/context.js +0 -262
- package/dist/core/auth/api/factors.js +0 -209
- package/dist/core/auth/api/index.js +0 -43
- package/dist/core/auth/api/profile.js +0 -243
- package/dist/core/auth/api/session.js +0 -312
- package/dist/core/auth/api/values.js +0 -90
- package/dist/core/auth/authorize.d.ts +0 -96
- package/dist/core/auth/authorize.js +0 -92
- package/dist/core/auth/createAuth.js +0 -216
- package/dist/core/auth/credentials.d.ts +0 -40
- package/dist/core/auth/credentials.js +0 -56
- package/dist/core/auth/csrf.d.ts +0 -143
- package/dist/core/auth/csrf.js +0 -295
- package/dist/core/auth/domains.d.ts +0 -41
- package/dist/core/auth/domains.js +0 -78
- package/dist/core/auth/identity.d.ts +0 -118
- package/dist/core/auth/identity.js +0 -194
- package/dist/core/auth/oauth/client.js +0 -52
- package/dist/core/auth/oauth/index.js +0 -130
- package/dist/core/auth/oauth/providers/github.js +0 -48
- package/dist/core/auth/oauth/providers/google.js +0 -30
- package/dist/core/auth/oauth/providers/oidc.js +0 -197
- package/dist/core/auth/oauth/state.js +0 -57
- package/dist/core/auth/oauth/types.js +0 -16
- package/dist/core/auth/passwords.d.ts +0 -15
- package/dist/core/auth/passwords.js +0 -32
- package/dist/core/auth/redirects.js +0 -31
- package/dist/core/auth/renewal.js +0 -24
- package/dist/core/auth/session.d.ts +0 -194
- package/dist/core/auth/session.js +0 -237
- package/dist/core/auth/sessionActivity.d.ts +0 -11
- package/dist/core/auth/sessionActivity.js +0 -14
- package/dist/core/auth/spaceTokens.d.ts +0 -173
- package/dist/core/auth/spaceTokens.js +0 -264
- package/dist/core/auth/tokens.d.ts +0 -224
- package/dist/core/auth/tokens.js +0 -264
- package/dist/core/auth/totp.js +0 -123
- package/dist/core/configSeam.d.ts +0 -10
- package/dist/core/configSeam.js +0 -151
- package/dist/core/createServer.js +0 -119
- package/dist/core/fontStore.js +0 -53
- package/dist/core/freePort.d.ts +0 -24
- package/dist/core/freePort.js +0 -74
- package/dist/core/handlers/authMiddleware.js +0 -38
- package/dist/core/handlers/authRouteHandlers.js +0 -112
- package/dist/core/handlers/csrfMiddleware.js +0 -56
- package/dist/core/handlers/oauthRouteHandlers.js +0 -161
- package/dist/core/handlers/socialRouteHandlers.js +0 -169
- package/dist/core/health.d.ts +0 -21
- package/dist/core/health.js +0 -40
- package/dist/core/http/dispatcher.d.ts +0 -15
- package/dist/core/http/dispatcher.js +0 -115
- package/dist/core/http/navigation.d.ts +0 -14
- package/dist/core/http/navigation.js +0 -19
- package/dist/core/http/securityHeaders.d.ts +0 -2
- package/dist/core/http/securityHeaders.js +0 -17
- package/dist/core/http/socketResponse.d.ts +0 -18
- package/dist/core/http/socketResponse.js +0 -59
- package/dist/core/http/sse.d.ts +0 -26
- package/dist/core/http/sse.js +0 -78
- package/dist/core/http/stages/authApi.js +0 -66
- package/dist/core/http/stages/authRoutes.js +0 -116
- package/dist/core/http/stages/crossSiteWrites.d.ts +0 -24
- package/dist/core/http/stages/crossSiteWrites.js +0 -45
- package/dist/core/http/stages/exchangeRoute.js +0 -69
- package/dist/core/http/stages/fontAssets.js +0 -27
- package/dist/core/http/stages/health.d.ts +0 -11
- package/dist/core/http/stages/health.js +0 -34
- package/dist/core/http/stages/images.js +0 -49
- package/dist/core/http/stages/livePages.js +0 -80
- package/dist/core/http/stages/middlewares.d.ts +0 -2
- package/dist/core/http/stages/middlewares.js +0 -23
- package/dist/core/http/stages/oauth.js +0 -118
- package/dist/core/http/stages/pluginAssets.js +0 -21
- package/dist/core/http/stages/sessionRenewal.js +0 -82
- package/dist/core/http/stages/signInRoute.js +0 -139
- package/dist/core/http/stages/static.js +0 -48
- package/dist/core/http/types.d.ts +0 -56
- package/dist/core/http/webExchange.d.ts +0 -18
- package/dist/core/http/webExchange.js +0 -53
- package/dist/core/mimeTypes.d.ts +0 -13
- package/dist/core/mimeTypes.js +0 -42
- package/dist/core/oauth/authorize.js +0 -279
- package/dist/core/oauth/challenge.js +0 -33
- package/dist/core/oauth/consentPage.js +0 -134
- package/dist/core/oauth/issueContext.js +0 -32
- package/dist/core/oauth/metadata.js +0 -71
- package/dist/core/oauth/params.js +0 -5
- package/dist/core/oauth/pkce.js +0 -15
- package/dist/core/oauth/records.js +0 -49
- package/dist/core/oauth/register.js +0 -76
- package/dist/core/oauth/respond.js +0 -59
- package/dist/core/oauth/token.js +0 -145
- package/dist/core/previewToken.d.ts +0 -21
- package/dist/core/previewToken.js +0 -32
- package/dist/core/requestParser.d.ts +0 -22
- package/dist/core/requestParser.js +0 -79
- package/dist/core/sdkAssets.js +0 -46
- package/dist/core/server/baseServer.d.ts +0 -30
- package/dist/core/server/baseServer.js +0 -106
- package/dist/core/server/closeOnSignals.d.ts +0 -28
- package/dist/core/server/closeOnSignals.js +0 -47
- package/dist/core/server/drain.d.ts +0 -18
- package/dist/core/server/drain.js +0 -82
- package/dist/core/server/fleet/channel.d.ts +0 -103
- package/dist/core/server/fleet/channel.js +0 -191
- package/dist/core/server/fleet/link.d.ts +0 -23
- package/dist/core/server/fleet/link.js +0 -70
- package/dist/core/server/fleet/relay.js +0 -112
- package/dist/core/server/fleet/role.d.ts +0 -46
- package/dist/core/server/fleet/role.js +0 -59
- package/dist/core/server/fleet/stores.d.ts +0 -21
- package/dist/core/server/fleet/stores.js +0 -46
- package/dist/core/server/fleet/supervisor.d.ts +0 -28
- package/dist/core/server/fleet/supervisor.js +0 -120
- package/dist/core/server/pageServer.js +0 -124
- package/dist/core/services/action.d.ts +0 -11
- package/dist/core/services/action.js +0 -123
- package/dist/core/services/functionRoutes.d.ts +0 -9
- package/dist/core/services/functionRoutes.js +0 -53
- package/dist/core/services/realtime.d.ts +0 -8
- package/dist/core/services/realtime.js +0 -62
- package/dist/core/services/registry.js +0 -47
- package/dist/core/services/resolve.js +0 -25
- package/dist/core/services/robotsTxt.js +0 -50
- package/dist/core/services/rsc.js +0 -13
- package/dist/core/services/servedSpace.js +0 -16
- package/dist/core/services/sitemapXml.js +0 -37
- package/dist/core/services/spaceDocument.js +0 -11
- package/dist/core/services/ssr.js +0 -13
- package/dist/core/staticFiles.d.ts +0 -3
- package/dist/core/staticFiles.js +0 -49
- package/dist/core/transports.d.ts +0 -31
- package/dist/core/transports.js +0 -61
- package/dist/core/unusedPort.d.ts +0 -10
- package/dist/core/unusedPort.js +0 -38
- package/dist/functions-api.d.ts +0 -679
- package/dist/functions.d.ts +0 -21
- package/dist/functions.js +0 -6
- package/dist/functionsRunner.d.ts +0 -20
- package/dist/functionsRunner.js +0 -7
- package/dist/helpers/atomicFile.d.ts +0 -10
- package/dist/helpers/atomicFile.js +0 -33
- package/dist/helpers/buildResponseHelpers.d.ts +0 -21
- package/dist/helpers/buildResponseHelpers.js +0 -84
- package/dist/helpers/buildServerInfo.js +0 -86
- package/dist/helpers/cache/CompressedFileCache.d.ts +0 -18
- package/dist/helpers/cache/CompressedFileCache.js +0 -44
- package/dist/helpers/cache/TtlCache.d.ts +0 -15
- package/dist/helpers/cache/TtlCache.js +0 -57
- package/dist/helpers/cache/cacheManager.js +0 -50
- package/dist/helpers/cache/defaults.js +0 -9
- package/dist/helpers/cache/keys.js +0 -130
- package/dist/helpers/cache/serverCaches.js +0 -15
- package/dist/helpers/compress.d.ts +0 -20
- package/dist/helpers/compress.js +0 -61
- package/dist/helpers/debugAuthorization.d.ts +0 -24
- package/dist/helpers/debugAuthorization.js +0 -27
- package/dist/helpers/escapeHtml.js +0 -13
- package/dist/helpers/escapeJson.js +0 -4
- package/dist/helpers/fileStore.d.ts +0 -60
- package/dist/helpers/fileStore.js +0 -127
- package/dist/helpers/flagOverrides.d.ts +0 -30
- package/dist/helpers/flagOverrides.js +0 -26
- package/dist/helpers/hydrationPayload.js +0 -57
- package/dist/helpers/metrics.js +0 -37
- package/dist/helpers/normalizePlugins.js +0 -16
- package/dist/helpers/offlineDataLoader.js +0 -15
- package/dist/helpers/onAbort.d.ts +0 -12
- package/dist/helpers/onAbort.js +0 -22
- package/dist/helpers/outboundGuard.d.ts +0 -64
- package/dist/helpers/outboundGuard.js +0 -218
- package/dist/helpers/paintedCookie.js +0 -13
- package/dist/helpers/readCookie.js +0 -11
- package/dist/helpers/reportReactBuild.js +0 -18
- package/dist/helpers/resolveDebugMode.js +0 -13
- package/dist/helpers/runMiddlewares.d.ts +0 -2
- package/dist/helpers/runMiddlewares.js +0 -21
- package/dist/helpers/serverLog.d.ts +0 -37
- package/dist/helpers/serverLog.js +0 -116
- package/dist/helpers/wsFrame.d.ts +0 -3
- package/dist/helpers/wsFrame.js +0 -5
- package/dist/hosts/authoringHost/index.js +0 -118
- package/dist/hosts/project/agentRuns.js +0 -107
- package/dist/hosts/project/laterAsks.js +0 -117
- package/dist/hosts/project/plugins.js +0 -185
- package/dist/hosts/project/serveProject.js +0 -396
- package/dist/hosts/project/spaceFailure.js +0 -86
- package/dist/hosts/project/watchSpace.js +0 -86
- package/dist/kernel.d.ts +0 -25
- package/dist/kernel.js +0 -10
- package/dist/middlewares/auth.d.ts +0 -2
- package/dist/middlewares/auth.js +0 -10
- package/dist/middlewares/basicAuth.d.ts +0 -6
- package/dist/middlewares/basicAuth.js +0 -67
- package/dist/middlewares/spaceDeployment.d.ts +0 -2
- package/dist/middlewares/spaceDeployment.js +0 -17
- package/dist/modules/actions/connectorWrite.d.ts +0 -11
- package/dist/modules/actions/connectorWrite.js +0 -83
- package/dist/modules/actions/index.d.ts +0 -78
- package/dist/modules/actions/index.js +0 -129
- package/dist/modules/actions/jobs/failureStreak.d.ts +0 -17
- package/dist/modules/actions/jobs/failureStreak.js +0 -47
- package/dist/modules/actions/jobs/fileQueue.d.ts +0 -34
- package/dist/modules/actions/jobs/fileQueue.js +0 -72
- package/dist/modules/actions/jobs/index.d.ts +0 -34
- package/dist/modules/actions/jobs/index.js +0 -60
- package/dist/modules/actions/jobs/later.d.ts +0 -43
- package/dist/modules/actions/jobs/later.js +0 -69
- package/dist/modules/actions/jobs/memoryQueue.d.ts +0 -33
- package/dist/modules/actions/jobs/memoryQueue.js +0 -42
- package/dist/modules/actions/jobs/queueDocument.d.ts +0 -14
- package/dist/modules/actions/jobs/queueDocument.js +0 -22
- package/dist/modules/actions/jobs/queueRules.d.ts +0 -39
- package/dist/modules/actions/jobs/queueRules.js +0 -270
- package/dist/modules/actions/jobs/scheduler.d.ts +0 -64
- package/dist/modules/actions/jobs/scheduler.js +0 -133
- package/dist/modules/actions/jobs/schedules.d.ts +0 -23
- package/dist/modules/actions/jobs/schedules.js +0 -47
- package/dist/modules/actions/jobs/storeClock.d.ts +0 -16
- package/dist/modules/actions/jobs/storeClock.js +0 -32
- package/dist/modules/actions/jobs/worker.d.ts +0 -67
- package/dist/modules/actions/jobs/worker.js +0 -361
- package/dist/modules/actions/moduleFor.d.ts +0 -3
- package/dist/modules/actions/moduleFor.js +0 -44
- package/dist/modules/actions/runtime/check.d.ts +0 -24
- package/dist/modules/actions/runtime/check.js +0 -122
- package/dist/modules/actions/runtime/credentials.d.ts +0 -10
- package/dist/modules/actions/runtime/credentials.js +0 -28
- package/dist/modules/actions/runtime/email.d.ts +0 -39
- package/dist/modules/actions/runtime/email.js +0 -91
- package/dist/modules/actions/runtime/errors.d.ts +0 -42
- package/dist/modules/actions/runtime/errors.js +0 -53
- package/dist/modules/actions/runtime/fileKv.d.ts +0 -35
- package/dist/modules/actions/runtime/fileKv.js +0 -81
- package/dist/modules/actions/runtime/flags.d.ts +0 -16
- package/dist/modules/actions/runtime/flags.js +0 -49
- package/dist/modules/actions/runtime/guards.d.ts +0 -144
- package/dist/modules/actions/runtime/guards.js +0 -255
- package/dist/modules/actions/runtime/kvChange.d.ts +0 -67
- package/dist/modules/actions/runtime/kvChange.js +0 -45
- package/dist/modules/actions/runtime/kvList.d.ts +0 -55
- package/dist/modules/actions/runtime/kvList.js +0 -56
- package/dist/modules/actions/runtime/kvStore.d.ts +0 -35
- package/dist/modules/actions/runtime/kvStore.js +0 -81
- package/dist/modules/actions/runtime/limits.d.ts +0 -11
- package/dist/modules/actions/runtime/limits.js +0 -35
- package/dist/modules/actions/runtime/memoryKv.d.ts +0 -28
- package/dist/modules/actions/runtime/memoryKv.js +0 -110
- package/dist/modules/actions/runtime/namespaceKv.d.ts +0 -9
- package/dist/modules/actions/runtime/namespaceKv.js +0 -35
- package/dist/modules/actions/runtime/precheck.d.ts +0 -27
- package/dist/modules/actions/runtime/precheck.js +0 -41
- package/dist/modules/actions/runtime/projectData.d.ts +0 -18
- package/dist/modules/actions/runtime/projectData.js +0 -69
- package/dist/modules/actions/runtime/rateLimit.d.ts +0 -26
- package/dist/modules/actions/runtime/rateLimit.js +0 -25
- package/dist/modules/actions/runtime/redisKv.d.ts +0 -27
- package/dist/modules/actions/runtime/redisKv.js +0 -46
- package/dist/modules/actions/runtime/renderResolver.d.ts +0 -16
- package/dist/modules/actions/runtime/renderResolver.js +0 -240
- package/dist/modules/actions/runtime/renderShare.d.ts +0 -12
- package/dist/modules/actions/runtime/renderShare.js +0 -70
- package/dist/modules/actions/runtime/report.d.ts +0 -14
- package/dist/modules/actions/runtime/report.js +0 -23
- package/dist/modules/actions/runtime/runAction.d.ts +0 -26
- package/dist/modules/actions/runtime/runAction.js +0 -606
- package/dist/modules/actions/runtime/runLogger.d.ts +0 -36
- package/dist/modules/actions/runtime/runLogger.js +0 -72
- package/dist/modules/actions/runtime/scope.d.ts +0 -40
- package/dist/modules/actions/runtime/scope.js +0 -129
- package/dist/modules/actions/runtime/signing.d.ts +0 -27
- package/dist/modules/actions/runtime/signing.js +0 -50
- package/dist/modules/actions/runtime/taskContext.d.ts +0 -51
- package/dist/modules/actions/runtime/taskContext.js +0 -125
- package/dist/modules/actions/runtime/triggers.d.ts +0 -12
- package/dist/modules/actions/runtime/triggers.js +0 -14
- package/dist/modules/actions/taskCatalog.d.ts +0 -28
- package/dist/modules/actions/taskCatalog.js +0 -25
- package/dist/modules/actions/tasks/auth.d.ts +0 -2
- package/dist/modules/actions/tasks/auth.js +0 -42
- package/dist/modules/actions/tasks/builtins.d.ts +0 -10
- package/dist/modules/actions/tasks/builtins.js +0 -32
- package/dist/modules/actions/tasks/connector.d.ts +0 -2
- package/dist/modules/actions/tasks/connector.js +0 -145
- package/dist/modules/actions/tasks/db.d.ts +0 -2
- package/dist/modules/actions/tasks/db.js +0 -59
- package/dist/modules/actions/tasks/email.d.ts +0 -2
- package/dist/modules/actions/tasks/email.js +0 -72
- package/dist/modules/actions/tasks/flow.d.ts +0 -3
- package/dist/modules/actions/tasks/flow.js +0 -282
- package/dist/modules/actions/tasks/helpers.d.ts +0 -16
- package/dist/modules/actions/tasks/helpers.js +0 -30
- package/dist/modules/actions/tasks/http.d.ts +0 -2
- package/dist/modules/actions/tasks/http.js +0 -111
- package/dist/modules/actions/tasks/kv.d.ts +0 -2
- package/dist/modules/actions/tasks/kv.js +0 -146
- package/dist/modules/actions/tasks/list.d.ts +0 -2
- package/dist/modules/actions/tasks/list.js +0 -154
- package/dist/modules/actions/tasks/realtime.d.ts +0 -2
- package/dist/modules/actions/tasks/realtime.js +0 -104
- package/dist/modules/actions/tasks/registry.d.ts +0 -26
- package/dist/modules/actions/tasks/registry.js +0 -63
- package/dist/modules/actions/tasks/transform.d.ts +0 -2
- package/dist/modules/actions/tasks/transform.js +0 -36
- package/dist/modules/actions/transport/callHandler.d.ts +0 -24
- package/dist/modules/actions/transport/callHandler.js +0 -296
- package/dist/modules/actions/transport/cancelHandler.d.ts +0 -23
- package/dist/modules/actions/transport/cancelHandler.js +0 -23
- package/dist/modules/actions/transport/catalogHandler.d.ts +0 -21
- package/dist/modules/actions/transport/catalogHandler.js +0 -22
- package/dist/modules/actions/transport/stream.d.ts +0 -22
- package/dist/modules/actions/transport/stream.js +0 -36
- package/dist/modules/actions/transport/verifySignature.d.ts +0 -16
- package/dist/modules/actions/transport/verifySignature.js +0 -72
- package/dist/modules/actions/transport/webhookHandler.d.ts +0 -25
- package/dist/modules/actions/transport/webhookHandler.js +0 -207
- package/dist/modules/actions/types.d.ts +0 -520
- package/dist/modules/connectors/engine.d.ts +0 -47
- package/dist/modules/connectors/engine.js +0 -222
- package/dist/modules/connectors/getByPath.d.ts +0 -8
- package/dist/modules/connectors/getByPath.js +0 -21
- package/dist/modules/connectors/index.d.ts +0 -7
- package/dist/modules/connectors/projection.d.ts +0 -18
- package/dist/modules/connectors/projection.js +0 -108
- package/dist/modules/connectors/resolver.d.ts +0 -27
- package/dist/modules/connectors/resolver.js +0 -74
- package/dist/modules/connectors/types.d.ts +0 -19
- package/dist/modules/functions/build.d.ts +0 -27
- package/dist/modules/functions/build.js +0 -216
- package/dist/modules/functions/capabilities.d.ts +0 -22
- package/dist/modules/functions/capabilities.js +0 -435
- package/dist/modules/functions/config.d.ts +0 -76
- package/dist/modules/functions/config.js +0 -40
- package/dist/modules/functions/context.d.ts +0 -20
- package/dist/modules/functions/context.js +0 -146
- package/dist/modules/functions/contract.d.ts +0 -329
- package/dist/modules/functions/contract.js +0 -9
- package/dist/modules/functions/driver.d.ts +0 -37
- package/dist/modules/functions/driver.js +0 -368
- package/dist/modules/functions/jobControl.d.ts +0 -21
- package/dist/modules/functions/jobControl.js +0 -43
- package/dist/modules/functions/jobs.d.ts +0 -98
- package/dist/modules/functions/jobs.js +0 -438
- package/dist/modules/functions/load.d.ts +0 -22
- package/dist/modules/functions/load.js +0 -49
- package/dist/modules/functions/local.d.ts +0 -31
- package/dist/modules/functions/local.js +0 -64
- package/dist/modules/functions/manifest.d.ts +0 -31
- package/dist/modules/functions/manifest.js +0 -337
- package/dist/modules/functions/native.d.ts +0 -9
- package/dist/modules/functions/native.js +0 -22
- package/dist/modules/functions/oauth.d.ts +0 -33
- package/dist/modules/functions/oauth.js +0 -360
- package/dist/modules/functions/protocol.d.ts +0 -344
- package/dist/modules/functions/protocol.js +0 -32
- package/dist/modules/functions/routes.d.ts +0 -51
- package/dist/modules/functions/routes.js +0 -242
- package/dist/modules/functions/runner/messages.d.ts +0 -4
- package/dist/modules/functions/runner/messages.js +0 -229
- package/dist/modules/functions/runner/remote.d.ts +0 -19
- package/dist/modules/functions/runner/remote.js +0 -168
- package/dist/modules/functions/runner/service.d.ts +0 -32
- package/dist/modules/functions/runner/service.js +0 -255
- package/dist/modules/functions/sandbox/guest/bytes.d.ts +0 -27
- package/dist/modules/functions/sandbox/guest/bytes.js +0 -108
- package/dist/modules/functions/sandbox/guest/crypto.d.ts +0 -47
- package/dist/modules/functions/sandbox/guest/crypto.js +0 -144
- package/dist/modules/functions/sandbox/guest/events.d.ts +0 -152
- package/dist/modules/functions/sandbox/guest/events.js +0 -143
- package/dist/modules/functions/sandbox/guest/fetch.d.ts +0 -305
- package/dist/modules/functions/sandbox/guest/fetch.js +0 -237
- package/dist/modules/functions/sandbox/guest/index.d.ts +0 -28
- package/dist/modules/functions/sandbox/guest/index.js +0 -130
- package/dist/modules/functions/sandbox/guest/types.d.ts +0 -38
- package/dist/modules/functions/sandbox/isolate.d.ts +0 -37
- package/dist/modules/functions/sandbox/isolate.js +0 -360
- package/dist/modules/functions/sandbox/prelude.d.ts +0 -2
- package/dist/modules/functions/sandbox/prelude.js +0 -49
- package/dist/modules/functions/scope.d.ts +0 -30
- package/dist/modules/functions/scope.js +0 -28
- package/dist/modules/functions/space.d.ts +0 -47
- package/dist/modules/functions/space.js +0 -185
- package/dist/modules/functions/tryEntry.d.ts +0 -9
- package/dist/modules/functions/tryEntry.js +0 -49
- package/dist/modules/images/allowlist.js +0 -18
- package/dist/modules/images/imageProxy.js +0 -291
- package/dist/modules/images/transform.js +0 -28
- package/dist/modules/mongo/index.d.ts +0 -4
- package/dist/modules/mongo/jobQueue.d.ts +0 -38
- package/dist/modules/mongo/jobQueue.js +0 -453
- package/dist/modules/mongo/kv.d.ts +0 -15
- package/dist/modules/mongo/kv.js +0 -129
- package/dist/modules/mysql/accounts.d.ts +0 -5
- package/dist/modules/mysql/accounts.js +0 -378
- package/dist/modules/mysql/admin.d.ts +0 -58
- package/dist/modules/mysql/admin.js +0 -133
- package/dist/modules/mysql/config.d.ts +0 -82
- package/dist/modules/mysql/config.js +0 -30
- package/dist/modules/mysql/identities.d.ts +0 -35
- package/dist/modules/mysql/identities.js +0 -43
- package/dist/modules/mysql/index.d.ts +0 -68
- package/dist/modules/mysql/index.js +0 -62
- package/dist/modules/mysql/jobs/index.d.ts +0 -5
- package/dist/modules/mysql/jobs/jobQueue.d.ts +0 -40
- package/dist/modules/mysql/jobs/jobQueue.js +0 -458
- package/dist/modules/mysql/jobs/kv.d.ts +0 -18
- package/dist/modules/mysql/jobs/kv.js +0 -108
- package/dist/modules/mysql/jobs/schema.d.ts +0 -28
- package/dist/modules/mysql/jobs/schema.js +0 -109
- package/dist/modules/mysql/pool.d.ts +0 -3
- package/dist/modules/mysql/pool.js +0 -88
- package/dist/modules/mysql/query.d.ts +0 -12
- package/dist/modules/mysql/query.js +0 -21
- package/dist/modules/mysql/schema.d.ts +0 -43
- package/dist/modules/mysql/schema.js +0 -390
- package/dist/modules/mysql/sessions.d.ts +0 -23
- package/dist/modules/mysql/sessions.js +0 -52
- package/dist/modules/mysql/spaceTokens.d.ts +0 -11
- package/dist/modules/mysql/spaceTokens.js +0 -59
- package/dist/modules/realtime/declarations.d.ts +0 -11
- package/dist/modules/realtime/declarations.js +0 -26
- package/dist/modules/realtime/failure.d.ts +0 -6
- package/dist/modules/realtime/failure.js +0 -11
- package/dist/modules/realtime/grants.d.ts +0 -23
- package/dist/modules/realtime/grants.js +0 -61
- package/dist/modules/realtime/handlers.d.ts +0 -85
- package/dist/modules/realtime/handlers.js +0 -266
- package/dist/modules/realtime/hub.d.ts +0 -71
- package/dist/modules/realtime/hub.js +0 -184
- package/dist/modules/realtime/index.d.ts +0 -75
- package/dist/modules/realtime/index.js +0 -89
- package/dist/modules/realtime/jobs.d.ts +0 -20
- package/dist/modules/realtime/jobs.js +0 -41
- package/dist/modules/realtime/memoryPubSub.d.ts +0 -10
- package/dist/modules/realtime/memoryPubSub.js +0 -43
- package/dist/modules/realtime/message.d.ts +0 -3
- package/dist/modules/realtime/message.js +0 -5
- package/dist/modules/realtime/presence.d.ts +0 -33
- package/dist/modules/realtime/presence.js +0 -56
- package/dist/modules/realtime/redisPubSub.d.ts +0 -24
- package/dist/modules/realtime/redisPubSub.js +0 -36
- package/dist/modules/realtime/retained.d.ts +0 -25
- package/dist/modules/realtime/retained.js +0 -47
- package/dist/modules/realtime/socket.d.ts +0 -30
- package/dist/modules/realtime/socket.js +0 -123
- package/dist/modules/rsc/connectorRscData.js +0 -79
- package/dist/modules/rsc/externalQueryReader.js +0 -43
- package/dist/modules/rsc/handler.js +0 -176
- package/dist/modules/rsc/matchRscPage.js +0 -26
- package/dist/modules/rsc/publicFileResolver.js +0 -73
- package/dist/modules/rsc/resolveRscData.js +0 -146
- package/dist/modules/runtime/bundle.d.ts +0 -29
- package/dist/modules/runtime/bundle.js +0 -117
- package/dist/modules/runtime/contract.d.ts +0 -37
- package/dist/modules/runtime/contract.js +0 -21
- package/dist/modules/runtime/host.d.ts +0 -38
- package/dist/modules/runtime/host.js +0 -68
- package/dist/modules/runtime/inside.d.ts +0 -36
- package/dist/modules/runtime/inside.js +0 -95
- package/dist/modules/runtime/runner.d.ts +0 -12
- package/dist/modules/runtime/runner.js +0 -48
- package/dist/modules/runtime/stages.d.ts +0 -53
- package/dist/modules/runtime/stages.js +0 -117
- package/dist/modules/sqlite/jobQueue.d.ts +0 -35
- package/dist/modules/sqlite/jobQueue.js +0 -56
- package/dist/modules/sqlite/kv.d.ts +0 -34
- package/dist/modules/sqlite/kv.js +0 -91
- package/dist/modules/sqlite/open.d.ts +0 -3
- package/dist/modules/sqlite/open.js +0 -13
- package/dist/modules/ssr/Component.js +0 -37
- package/dist/modules/ssr/applySSRResult.js +0 -54
- package/dist/modules/ssr/buildBody.js +0 -35
- package/dist/modules/ssr/handler.js +0 -103
- package/dist/modules/ssr/loadPluginComponents.js +0 -81
- package/dist/modules/ssr/prepareRender.js +0 -332
- package/dist/modules/ssr/preview.js +0 -70
- package/dist/modules/ssr/registerExternalPlugins.js +0 -111
- package/dist/modules/ssr/reportMissingPlugins.js +0 -24
- package/dist/modules/ssr/resolvePageSeo.js +0 -41
- package/dist/modules/ssr/spaceDocument.js +0 -85
- package/dist/modules/ssr/streamBody.js +0 -69
- package/dist/modules/ssr/template.js +0 -10
- package/dist/mongo.d.ts +0 -25
- package/dist/mongo.js +0 -3
- package/dist/mysql.d.ts +0 -37
- package/dist/mysql.js +0 -7
- package/dist/plugins/compile.js +0 -53
- package/dist/plugins/copy.js +0 -28
- package/dist/plugins/detect.js +0 -9
- package/dist/plugins/manager.js +0 -508
- package/dist/plugins/validate.js +0 -23
- package/dist/plugins/watch.js +0 -79
- package/dist/runtime.d.ts +0 -16
- package/dist/runtime.js +0 -7
- package/dist/sqlite.d.ts +0 -24
- package/dist/sqlite.js +0 -3
|
@@ -0,0 +1,2118 @@
|
|
|
1
|
+
import { schemaFromWire } from "@plitzi/sdk-shared/schema";
|
|
2
|
+
import { compressBody, frameAncestorsOf, requestAuthority, requestOrigin } from "@plitzi/sdk-kernel/http";
|
|
3
|
+
import { serverLog } from "@plitzi/sdk-kernel/log";
|
|
4
|
+
import { flagsCookieName } from "@plitzi/sdk-shared/flags";
|
|
5
|
+
import { TRUSTED_TYPES_POLICIES, getKeyDecoded, isRecord } from "@plitzi/sdk-shared/helpers";
|
|
6
|
+
import { paintedKeys, paintedStateCookieName, paintedStateFor } from "@plitzi/sdk-shared/state";
|
|
7
|
+
import { frameAncestors, sessionCookieParams, sessionHintCookieName } from "@plitzi/sdk-kernel/identity";
|
|
8
|
+
import { TtlCache } from "@plitzi/sdk-kernel/cache";
|
|
9
|
+
import { debugCookieName } from "@plitzi/sdk-shared/devTools";
|
|
10
|
+
import { requestScheme, themeFromCookies } from "@plitzi/sdk-shared/theme/cookie";
|
|
11
|
+
import { brotliDecompressSync, gunzipSync } from "node:zlib";
|
|
12
|
+
import { createHash, randomBytes, randomUUID } from "node:crypto";
|
|
13
|
+
import { styleSheetCss, styleSheetHref, styleSheetLinkable } from "@plitzi/sdk-shared/style";
|
|
14
|
+
import { readFileSync, statSync, writeFileSync } from "node:fs";
|
|
15
|
+
// src/helpers/paintedCookie.ts
|
|
16
|
+
/**
|
|
17
|
+
* The name the painted state of a server-rendered page is kept under, for this request's host.
|
|
18
|
+
*
|
|
19
|
+
* The page this server sends carries no `webKey`, so the SDK keeps its state under the web id an empty key decodes to —
|
|
20
|
+
* the same one its web storage key uses. One helper for both readers of the cookie, the render and the HTML cache key,
|
|
21
|
+
* so they cannot come to disagree about which cookie the page was drawn from.
|
|
22
|
+
*/
|
|
23
|
+
var ssrPaintedCookieName = (host) => paintedStateCookieName(getKeyDecoded("", true), host);
|
|
24
|
+
/**
|
|
25
|
+
* The state a server-rendered page starts from on this request — the keys the space paints, as the visitor's cookie
|
|
26
|
+
* holds them — and which keys those are. One answer for the render (the SDK's starting `runtime.state`) and the page's
|
|
27
|
+
* server providers (`{{ state.workspace.id }}` in a `query`), so a provider asks with the value the page is drawn with.
|
|
28
|
+
* Only with `keepState` on, and of an entry another account wrote than the one this request proved, only the browser's
|
|
29
|
+
* keys (`browserState`).
|
|
30
|
+
*/
|
|
31
|
+
var requestPaintedState = (req, settings, account) => {
|
|
32
|
+
if (!settings?.keepState) return {
|
|
33
|
+
keys: /* @__PURE__ */ new Set(),
|
|
34
|
+
state: void 0
|
|
35
|
+
};
|
|
36
|
+
return {
|
|
37
|
+
keys: paintedKeys(settings),
|
|
38
|
+
state: paintedStateFor(req.headers.cookie, ssrPaintedCookieName(requestAuthority(req)), settings, account)
|
|
39
|
+
};
|
|
40
|
+
};
|
|
41
|
+
// src/helpers/cache/defaults.ts
|
|
42
|
+
var DEFAULT_TTL_MS = {
|
|
43
|
+
html: 3e5,
|
|
44
|
+
rsc: 3e4,
|
|
45
|
+
offlineData: 3e5,
|
|
46
|
+
stale: 6e4
|
|
47
|
+
};
|
|
48
|
+
/**
|
|
49
|
+
* What each cache of one process may hold, in bytes. Bounded by bytes because entries are anything but alike: a
|
|
50
|
+
* landing page's documents are a megabyte, a blog post's answer a few KB — 500 entries was 5 MB or 500 MB.
|
|
51
|
+
*/
|
|
52
|
+
var DEFAULT_CACHE_BYTES = {
|
|
53
|
+
html: 134217728,
|
|
54
|
+
/** The pages every replica shares (`createRedisPageStore`). */
|
|
55
|
+
store: 134217728,
|
|
56
|
+
rsc: 16777216,
|
|
57
|
+
offlineData: 33554432
|
|
58
|
+
};
|
|
59
|
+
/**
|
|
60
|
+
* The parameters a link carries for analytics: a page is rendered and cached as if they were absent — every campaign
|
|
61
|
+
* link would otherwise be a page of its own, rendered for the one visitor who followed it.
|
|
62
|
+
*/
|
|
63
|
+
var DEFAULT_IGNORED_QUERY_PARAMS = [
|
|
64
|
+
"utm_*",
|
|
65
|
+
"fbclid",
|
|
66
|
+
"gclid",
|
|
67
|
+
"gbraid",
|
|
68
|
+
"wbraid",
|
|
69
|
+
"dclid",
|
|
70
|
+
"msclkid",
|
|
71
|
+
"yclid",
|
|
72
|
+
"twclid",
|
|
73
|
+
"ttclid",
|
|
74
|
+
"li_fat_id",
|
|
75
|
+
"igshid",
|
|
76
|
+
"mc_cid",
|
|
77
|
+
"mc_eid",
|
|
78
|
+
"_ga",
|
|
79
|
+
"_gl",
|
|
80
|
+
"_hsenc",
|
|
81
|
+
"_hsmi",
|
|
82
|
+
"mkt_tok"
|
|
83
|
+
];
|
|
84
|
+
// src/helpers/readCookie.ts
|
|
85
|
+
var readCookie = (cookieHeader, name) => {
|
|
86
|
+
if (!cookieHeader) return;
|
|
87
|
+
for (const part of cookieHeader.split(";")) {
|
|
88
|
+
const eq = part.indexOf("=");
|
|
89
|
+
if (eq === -1) continue;
|
|
90
|
+
if (part.slice(0, eq).trim() === name) return decodeURIComponent(part.slice(eq + 1).trim());
|
|
91
|
+
}
|
|
92
|
+
};
|
|
93
|
+
// src/helpers/visitorScheme.ts
|
|
94
|
+
/** The client hint a page asks Chromium for (`Accept-CH`), and that the document therefore varies by. */
|
|
95
|
+
var SCHEME_HINT_HEADER = "Sec-CH-Prefers-Color-Scheme";
|
|
96
|
+
/** The scheme the visitor's machine asks for, as this request says it: the client hint, else the SDK's cookie. */
|
|
97
|
+
var visitorScheme = (req) => {
|
|
98
|
+
const hint = req.headers["sec-ch-prefers-color-scheme"];
|
|
99
|
+
return requestScheme(req.headers.cookie, typeof hint === "string" ? hint : void 0);
|
|
100
|
+
};
|
|
101
|
+
// src/helpers/cache/queryParams.ts
|
|
102
|
+
/** The parameters this server renders and caches a page without — `cache.ignoredQueryParams`, or the analytics ones. */
|
|
103
|
+
var ignoredQueryParamsOf = (config) => config.cache?.ignoredQueryParams ?? DEFAULT_IGNORED_QUERY_PARAMS;
|
|
104
|
+
var isIgnored = (name, ignored) => ignored.some((pattern) => pattern.endsWith("*") ? name.startsWith(pattern.slice(0, -1)) : name === pattern);
|
|
105
|
+
/**
|
|
106
|
+
* The query string as a cache key reads it: without the ignored parameters, and in one order. `?b=2&a=1` and
|
|
107
|
+
* `?a=1&b=2` are the same page, and were two renders. The order of a name given twice is kept — that one a page can
|
|
108
|
+
* tell apart.
|
|
109
|
+
*/
|
|
110
|
+
var canonicalSearch = (search, ignored) => {
|
|
111
|
+
if (search === "" || search === "?") return "";
|
|
112
|
+
const params = [...new URLSearchParams(search.slice(1))].filter(([name]) => !isIgnored(name, ignored));
|
|
113
|
+
if (params.length === 0) return "";
|
|
114
|
+
params.sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
|
|
115
|
+
return `?${new URLSearchParams(params).toString()}`;
|
|
116
|
+
};
|
|
117
|
+
/** The query a page is rendered with: what it was asked with, less the ignored parameters. */
|
|
118
|
+
var renderedQuery = (query, ignored) => {
|
|
119
|
+
const kept = Object.entries(query).filter(([name]) => !isIgnored(name, ignored));
|
|
120
|
+
return kept.length === Object.keys(query).length ? query : Object.fromEntries(kept);
|
|
121
|
+
};
|
|
122
|
+
// src/helpers/cache/keys.ts
|
|
123
|
+
var flagsVersionOf = (req) => req.ctx?.spaceDeployment?.flagsVersion ?? "";
|
|
124
|
+
var draftVersionOf = (req) => req.ctx?.spaceDeployment?.draftVersion ?? "";
|
|
125
|
+
/** The fields of an HTML key, in the order they are joined. */
|
|
126
|
+
var HTML_KEY_FIELDS = [
|
|
127
|
+
"accessToken",
|
|
128
|
+
"spaceId",
|
|
129
|
+
"environment",
|
|
130
|
+
"revision",
|
|
131
|
+
"flags",
|
|
132
|
+
"draft",
|
|
133
|
+
"theme",
|
|
134
|
+
"scheme",
|
|
135
|
+
"painted",
|
|
136
|
+
"debugHidden",
|
|
137
|
+
"forcedFlags",
|
|
138
|
+
"hostname",
|
|
139
|
+
"path",
|
|
140
|
+
"search"
|
|
141
|
+
];
|
|
142
|
+
/**
|
|
143
|
+
* The key a rendered document is cached under.
|
|
144
|
+
*
|
|
145
|
+
* The visitor's theme is part of it because it is part of the DOCUMENT: `prepareRender` reads the `theme` cookie and
|
|
146
|
+
* writes it onto `<html>` and into the props the SDK hydrates with. Keyed without it, the first visitor's choice was
|
|
147
|
+
* served to everybody behind them — a dark page for a visitor who chose light, then corrected on hydration.
|
|
148
|
+
*
|
|
149
|
+
* So is whether the visitor hid the dev tools, on a page that authorizes them: the render leaves the panel out for
|
|
150
|
+
* them and in for everybody else. It is the only value of that cookie that changes what is drawn, so it is the only
|
|
151
|
+
* one keyed — a space that switched dev tools on for its published site would otherwise hand the first visitor's
|
|
152
|
+
* choice to the rest.
|
|
153
|
+
*
|
|
154
|
+
* So is the kept state the first paint depends on (`settings.paintedState`): `prepareRender` renders with that cookie's
|
|
155
|
+
* values, so a page drawn with one visitor's toolbar must not be served to the next. Keyed by its raw value — this
|
|
156
|
+
* key does not know which keys a space declares, and a space that declares none has no such cookie to split on.
|
|
157
|
+
*
|
|
158
|
+
* So are the feature flags a tester forced from the dev tools, on a page that authorizes debugging: drawn with them,
|
|
159
|
+
* the page is not everybody's, and a tester holding the cookie must never be handed a page drawn without it. Keyed
|
|
160
|
+
* by its raw value, like the kept state.
|
|
161
|
+
*
|
|
162
|
+
* So is what the space's flags are at (`flagsVersion` on the resolved deployment), for a deployment that changes them
|
|
163
|
+
* apart from its revisions: a flag turned in production must reach the next visitor, while the revision is the same.
|
|
164
|
+
*
|
|
165
|
+
* Read from the request here rather than handed in, so a call site cannot key the page without it. Only those
|
|
166
|
+
* cookies are read: keying the whole header would split the cache on every analytics cookie a visitor carries. The
|
|
167
|
+
* query string is keyed as the page is rendered from it (`canonicalSearch`): without the parameters it is rendered
|
|
168
|
+
* without, and in one order.
|
|
169
|
+
*/
|
|
170
|
+
var buildHtmlCacheKey = (accessToken = "anonymous", spaceId, environment, revision, req, ignoredQueryParams) => {
|
|
171
|
+
const fields = {
|
|
172
|
+
accessToken,
|
|
173
|
+
spaceId: String(spaceId ?? 1),
|
|
174
|
+
environment,
|
|
175
|
+
revision: String(revision),
|
|
176
|
+
flags: flagsVersionOf(req),
|
|
177
|
+
draft: draftVersionOf(req),
|
|
178
|
+
theme: themeFromCookies(req.headers.cookie) ?? "",
|
|
179
|
+
scheme: [void 0, "system"].includes(themeFromCookies(req.headers.cookie)) ? visitorScheme(req) ?? "" : "",
|
|
180
|
+
painted: readCookie(req.headers.cookie, ssrPaintedCookieName(requestAuthority(req))) ?? "",
|
|
181
|
+
debugHidden: readCookie(req.headers.cookie, debugCookieName(requestAuthority(req))) === "false" ? "debug-off" : "",
|
|
182
|
+
forcedFlags: readCookie(req.headers.cookie, flagsCookieName(requestAuthority(req))) ?? "",
|
|
183
|
+
hostname: req.hostname,
|
|
184
|
+
path: req.path,
|
|
185
|
+
search: canonicalSearch(req.search, ignoredQueryParams)
|
|
186
|
+
};
|
|
187
|
+
return HTML_KEY_FIELDS.map((field) => fields[field]).join("\0");
|
|
188
|
+
};
|
|
189
|
+
/** One field of a key joined from `fields`, read back by the same list: never by a position written down twice. */
|
|
190
|
+
var fieldOf = (fields, key, field) => key.split("\0")[fields.indexOf(field)] ?? "";
|
|
191
|
+
/**
|
|
192
|
+
* What an HTML key says about the page it holds, read by the one list that also writes it. `server.cache.invalidate`
|
|
193
|
+
* filters on these; it used to split the key by positions of its own, and when the key grew a field in front the
|
|
194
|
+
* filter went on reading the wrong ones — every invalidation by space matched nothing.
|
|
195
|
+
*/
|
|
196
|
+
var readHtmlCacheKey = (key) => ({
|
|
197
|
+
spaceId: fieldOf(HTML_KEY_FIELDS, key, "spaceId"),
|
|
198
|
+
environment: fieldOf(HTML_KEY_FIELDS, key, "environment"),
|
|
199
|
+
hostname: fieldOf(HTML_KEY_FIELDS, key, "hostname")
|
|
200
|
+
});
|
|
201
|
+
var OFFLINE_DATA_KEY_FIELDS = [
|
|
202
|
+
"spaceId",
|
|
203
|
+
"environment",
|
|
204
|
+
"revision",
|
|
205
|
+
"flags",
|
|
206
|
+
"draft"
|
|
207
|
+
];
|
|
208
|
+
/**
|
|
209
|
+
* The space as read for a render: its revision, what its flags are at when they change apart from it, and — for the
|
|
210
|
+
* draft — what the draft is at.
|
|
211
|
+
*/
|
|
212
|
+
var buildOfflineDataCacheKey = (spaceId, environment, revision, flagsVersion, draftVersion) => {
|
|
213
|
+
const fields = {
|
|
214
|
+
spaceId: String(spaceId),
|
|
215
|
+
environment,
|
|
216
|
+
revision: String(revision),
|
|
217
|
+
flags: flagsVersion ?? "",
|
|
218
|
+
draft: draftVersion ?? ""
|
|
219
|
+
};
|
|
220
|
+
return OFFLINE_DATA_KEY_FIELDS.map((field) => fields[field]).join("\0");
|
|
221
|
+
};
|
|
222
|
+
/**
|
|
223
|
+
* Whether what a request renders may be kept for the next: a published revision always — it never changes under its
|
|
224
|
+
* name — and the draft (`main`), which changes with every edit someone is making right then, only when the deployment
|
|
225
|
+
* says what it is at (`draftVersion`), which every such edit changes. Without it a draft is read and drawn every time.
|
|
226
|
+
*/
|
|
227
|
+
var keepsVersion = (deployment) => (deployment?.environment ?? "main") !== "main" || deployment?.draftVersion !== void 0;
|
|
228
|
+
/** Where the space a request resolves to is kept between renders, or nothing when it may not be (`keepsVersion`). */
|
|
229
|
+
var offlineDataCacheKeyOf = (deployment) => keepsVersion(deployment) ? buildOfflineDataCacheKey(deployment?.spaceId ?? 1, deployment?.environment ?? "main", deployment?.revision ?? 0, deployment?.flagsVersion, deployment?.draftVersion) : void 0;
|
|
230
|
+
var readOfflineDataCacheKey = (key) => ({
|
|
231
|
+
spaceId: fieldOf(OFFLINE_DATA_KEY_FIELDS, key, "spaceId"),
|
|
232
|
+
environment: fieldOf(OFFLINE_DATA_KEY_FIELDS, key, "environment")
|
|
233
|
+
});
|
|
234
|
+
var RSC_KEY_FIELDS = [
|
|
235
|
+
"spaceId",
|
|
236
|
+
"environment",
|
|
237
|
+
"revision",
|
|
238
|
+
"flags",
|
|
239
|
+
"user",
|
|
240
|
+
"ids",
|
|
241
|
+
"hostname",
|
|
242
|
+
"path",
|
|
243
|
+
"search"
|
|
244
|
+
];
|
|
245
|
+
var buildRscCacheKey = (spaceId, environment, revision, userId, idsParam, req) => {
|
|
246
|
+
const fields = {
|
|
247
|
+
spaceId: String(spaceId),
|
|
248
|
+
environment,
|
|
249
|
+
revision: String(revision),
|
|
250
|
+
flags: flagsVersionOf(req),
|
|
251
|
+
user: userId === void 0 ? "anon" : String(userId),
|
|
252
|
+
ids: idsParam ?? "",
|
|
253
|
+
hostname: req.hostname,
|
|
254
|
+
path: req.path,
|
|
255
|
+
search: req.search
|
|
256
|
+
};
|
|
257
|
+
return RSC_KEY_FIELDS.map((field) => fields[field]).join("\0");
|
|
258
|
+
};
|
|
259
|
+
var readRscCacheKey = (key) => ({
|
|
260
|
+
spaceId: fieldOf(RSC_KEY_FIELDS, key, "spaceId"),
|
|
261
|
+
environment: fieldOf(RSC_KEY_FIELDS, key, "environment"),
|
|
262
|
+
hostname: fieldOf(RSC_KEY_FIELDS, key, "hostname")
|
|
263
|
+
});
|
|
264
|
+
// src/helpers/cache/cacheManager.ts
|
|
265
|
+
/**
|
|
266
|
+
* Whether an entry is one the filter names. An entry that is not any one host's (the space as read for a render) is
|
|
267
|
+
* named by a filter on a host too: the page that host serves is rendered from it, and dropping the page while keeping
|
|
268
|
+
* it would render the same page again.
|
|
269
|
+
*/
|
|
270
|
+
var matches = (facts, filter) => (filter.spaceId === void 0 || facts.spaceId === String(filter.spaceId)) && (filter.environment === void 0 || facts.environment === filter.environment) && (filter.hostname === void 0 || facts.hostname === void 0 || facts.hostname === filter.hostname);
|
|
271
|
+
var clearCounted = (store) => {
|
|
272
|
+
const count = store.size;
|
|
273
|
+
store.clear();
|
|
274
|
+
return count;
|
|
275
|
+
};
|
|
276
|
+
/**
|
|
277
|
+
* `server.cache` over every cache a render is kept in: the pages, the RSC answers, and the space as read for both.
|
|
278
|
+
*
|
|
279
|
+
* All three, because they hold one change between them. Dropping the pages alone left the space they were rendered
|
|
280
|
+
* from, and the next request rendered the page that had just been dropped from it — an invalidation that cleared
|
|
281
|
+
* every page and changed none of them.
|
|
282
|
+
*/
|
|
283
|
+
var buildCacheManager = ({ html, rsc, offlineData }) => {
|
|
284
|
+
const caches = [
|
|
285
|
+
...html ? [{
|
|
286
|
+
store: html,
|
|
287
|
+
read: readHtmlCacheKey
|
|
288
|
+
}] : [],
|
|
289
|
+
...rsc ? [{
|
|
290
|
+
store: rsc,
|
|
291
|
+
read: readRscCacheKey
|
|
292
|
+
}] : [],
|
|
293
|
+
...offlineData ? [{
|
|
294
|
+
store: offlineData,
|
|
295
|
+
read: readOfflineDataCacheKey
|
|
296
|
+
}] : []
|
|
297
|
+
];
|
|
298
|
+
return {
|
|
299
|
+
invalidate(filter) {
|
|
300
|
+
if (!filter || Object.keys(filter).length === 0) return caches.reduce((count, { store }) => count + clearCounted(store), 0);
|
|
301
|
+
return caches.reduce((count, { store, read }) => count + store.invalidateWhere((key) => matches(read(key), filter)), 0);
|
|
302
|
+
},
|
|
303
|
+
clear() {
|
|
304
|
+
caches.forEach(({ store }) => store.clear());
|
|
305
|
+
},
|
|
306
|
+
get size() {
|
|
307
|
+
return caches.reduce((count, { store }) => count + store.size, 0);
|
|
308
|
+
}
|
|
309
|
+
};
|
|
310
|
+
};
|
|
311
|
+
// src/helpers/cache/pages.ts
|
|
312
|
+
var keepPage = (html, compression, nonce) => {
|
|
313
|
+
const encoding = compression.encodings.at(0);
|
|
314
|
+
if (!encoding) return {
|
|
315
|
+
html,
|
|
316
|
+
compressed: {},
|
|
317
|
+
nonce
|
|
318
|
+
};
|
|
319
|
+
const body = compressBody(html, encoding, compression, true);
|
|
320
|
+
return typeof body === "string" ? {
|
|
321
|
+
html,
|
|
322
|
+
compressed: {},
|
|
323
|
+
nonce
|
|
324
|
+
} : {
|
|
325
|
+
compressed: { [encoding]: body },
|
|
326
|
+
nonce
|
|
327
|
+
};
|
|
328
|
+
};
|
|
329
|
+
var pageHtml = (page) => {
|
|
330
|
+
if (page.html !== void 0) return page.html;
|
|
331
|
+
if (page.compressed.br) return brotliDecompressSync(page.compressed.br).toString("utf-8");
|
|
332
|
+
if (page.compressed.gzip) return gunzipSync(page.compressed.gzip).toString("utf-8");
|
|
333
|
+
return "";
|
|
334
|
+
};
|
|
335
|
+
/** What a kept page costs, in bytes: its compressed bodies, and its HTML when it is kept as it is. */
|
|
336
|
+
var sizeOfPage = (page) => (page.html?.length ?? 0) + (page.compressed.br?.length ?? 0) + (page.compressed.gzip?.length ?? 0);
|
|
337
|
+
var toSharedPage = (page, renderedAt) => {
|
|
338
|
+
const { nonce } = page;
|
|
339
|
+
if (page.compressed.br) return {
|
|
340
|
+
encoding: "br",
|
|
341
|
+
body: page.compressed.br,
|
|
342
|
+
renderedAt,
|
|
343
|
+
nonce
|
|
344
|
+
};
|
|
345
|
+
if (page.compressed.gzip) return {
|
|
346
|
+
encoding: "gzip",
|
|
347
|
+
body: page.compressed.gzip,
|
|
348
|
+
renderedAt,
|
|
349
|
+
nonce
|
|
350
|
+
};
|
|
351
|
+
return {
|
|
352
|
+
encoding: "identity",
|
|
353
|
+
body: Buffer.from(page.html ?? "", "utf-8"),
|
|
354
|
+
renderedAt,
|
|
355
|
+
nonce
|
|
356
|
+
};
|
|
357
|
+
};
|
|
358
|
+
var fromSharedPage = ({ encoding, body, nonce }) => encoding === "identity" ? {
|
|
359
|
+
html: body.toString("utf-8"),
|
|
360
|
+
compressed: {},
|
|
361
|
+
nonce
|
|
362
|
+
} : {
|
|
363
|
+
compressed: { [encoding]: body },
|
|
364
|
+
nonce
|
|
365
|
+
};
|
|
366
|
+
// src/modules/ssr/renderTurns.ts
|
|
367
|
+
var createRenderTurns = () => {
|
|
368
|
+
const refused = busyLog();
|
|
369
|
+
const spaces = /* @__PURE__ */ new Map();
|
|
370
|
+
const turnsOf = (spaceId) => {
|
|
371
|
+
const existing = spaces.get(spaceId);
|
|
372
|
+
if (existing) return existing;
|
|
373
|
+
const created = {
|
|
374
|
+
running: 0,
|
|
375
|
+
waiting: []
|
|
376
|
+
};
|
|
377
|
+
spaces.set(spaceId, created);
|
|
378
|
+
return created;
|
|
379
|
+
};
|
|
380
|
+
/** Given back once, whoever calls it twice: the turn passes to the first waiting, or the count drops. */
|
|
381
|
+
const releaseOf = (spaceId, turns) => {
|
|
382
|
+
let released = false;
|
|
383
|
+
return () => {
|
|
384
|
+
if (released) return;
|
|
385
|
+
released = true;
|
|
386
|
+
const next = turns.waiting.shift();
|
|
387
|
+
if (next) {
|
|
388
|
+
next(releaseOf(spaceId, turns));
|
|
389
|
+
return;
|
|
390
|
+
}
|
|
391
|
+
turns.running--;
|
|
392
|
+
if (turns.running === 0) spaces.delete(spaceId);
|
|
393
|
+
};
|
|
394
|
+
};
|
|
395
|
+
const tryTake = (spaceId, limit) => {
|
|
396
|
+
const turns = turnsOf(spaceId);
|
|
397
|
+
if (turns.running >= limit) return;
|
|
398
|
+
turns.running++;
|
|
399
|
+
return releaseOf(spaceId, turns);
|
|
400
|
+
};
|
|
401
|
+
const take = (spaceId, limit, waitMs) => {
|
|
402
|
+
const now = tryTake(spaceId, limit);
|
|
403
|
+
if (now || waitMs <= 0) return Promise.resolve(now);
|
|
404
|
+
const turns = turnsOf(spaceId);
|
|
405
|
+
return new Promise((resolve) => {
|
|
406
|
+
const waiter = (release) => {
|
|
407
|
+
clearTimeout(timer);
|
|
408
|
+
resolve(release);
|
|
409
|
+
};
|
|
410
|
+
const timer = setTimeout(() => {
|
|
411
|
+
turns.waiting.splice(turns.waiting.indexOf(waiter), 1);
|
|
412
|
+
resolve(void 0);
|
|
413
|
+
}, waitMs);
|
|
414
|
+
turns.waiting.push(waiter);
|
|
415
|
+
});
|
|
416
|
+
};
|
|
417
|
+
return {
|
|
418
|
+
take,
|
|
419
|
+
tryTake,
|
|
420
|
+
running: (spaceId) => spaces.get(spaceId)?.running ?? 0,
|
|
421
|
+
refused
|
|
422
|
+
};
|
|
423
|
+
};
|
|
424
|
+
/** How long a page past its space's limit waits for a turn, unless the server says (`renderLimit.waitMs`). */
|
|
425
|
+
var DEFAULT_RENDER_WAIT_MS = 2e3;
|
|
426
|
+
var isCount = (value) => typeof value === "number" && Number.isInteger(value) && value >= 1;
|
|
427
|
+
/** The server's `renderLimit`, refused at boot when it says no count — rather than a space that never renders. */
|
|
428
|
+
var renderLimitOf = (config) => {
|
|
429
|
+
if (!config) return;
|
|
430
|
+
if (config.perSpace !== void 0 && !isCount(config.perSpace)) throw new Error(`renderLimit.perSpace: ${String(config.perSpace)} is no count of renders — write a whole number, 1 or more`);
|
|
431
|
+
if (config.waitMs !== void 0 && !(Number.isFinite(config.waitMs) && config.waitMs >= 0)) throw new Error(`renderLimit.waitMs: ${String(config.waitMs)} is no wait — write milliseconds, 0 or more`);
|
|
432
|
+
return {
|
|
433
|
+
...config,
|
|
434
|
+
waitMs: config.waitMs ?? 2e3
|
|
435
|
+
};
|
|
436
|
+
};
|
|
437
|
+
/** The limit a page of `deployment` renders under: its own, else the server's; none without either. */
|
|
438
|
+
var renderLimitFor = (deployment, config) => {
|
|
439
|
+
const own = deployment?.renderLimit;
|
|
440
|
+
if (own !== void 0) {
|
|
441
|
+
if (isCount(own)) return own;
|
|
442
|
+
serverLog.warn("SSR render limit", `space ${String(deployment?.spaceId)}: renderLimit ${String(own)} is no count of renders — the server's is used`);
|
|
443
|
+
}
|
|
444
|
+
return config?.perSpace;
|
|
445
|
+
};
|
|
446
|
+
/**
|
|
447
|
+
* The pages of each space answered 503 for want of a turn, said once a minute per space with how many: a burst is
|
|
448
|
+
* thousands of them, and one line each would bury everything else the server says.
|
|
449
|
+
*/
|
|
450
|
+
var busyLog = (now = Date.now) => {
|
|
451
|
+
const said = /* @__PURE__ */ new Map();
|
|
452
|
+
return (spaceId, limit) => {
|
|
453
|
+
const last = said.get(spaceId);
|
|
454
|
+
if (last && now() - last.at < 6e4) {
|
|
455
|
+
last.count++;
|
|
456
|
+
return;
|
|
457
|
+
}
|
|
458
|
+
const count = (last?.count ?? 0) + 1;
|
|
459
|
+
said.set(spaceId, {
|
|
460
|
+
at: now(),
|
|
461
|
+
count: 0
|
|
462
|
+
});
|
|
463
|
+
serverLog.warn("SSR render limit", `space ${String(spaceId)}: ${String(count)} page${count === 1 ? "" : "s"} answered 503 — ${String(limit)} of its pages were rendering already (renderLimit)`);
|
|
464
|
+
};
|
|
465
|
+
};
|
|
466
|
+
// src/helpers/escapeJson.ts
|
|
467
|
+
var escapeJson = (str) => str.replace(/</g, "\\u003c").replace(/>/g, "\\u003e").replace(/&/g, "\\u0026").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
|
|
468
|
+
// src/helpers/hydrationPayload.ts
|
|
469
|
+
var digest = (text) => createHash("sha256").update(text).digest("base64url").slice(0, 22);
|
|
470
|
+
var sent = /* @__PURE__ */ new WeakMap();
|
|
471
|
+
/**
|
|
472
|
+
* The space with `schema` — the one a visitor is sent, some pages withheld (`withholdPages`) — as the same object for
|
|
473
|
+
* every visitor sent that schema. Everything kept by the object is kept for them too: a new one each render made the
|
|
474
|
+
* page's document be written, escaped and hashed again for every visit to a space with one protected page (a quarter
|
|
475
|
+
* of what the docs' pages cost, measured). `schema` is the space's own when nothing is withheld, and the space is
|
|
476
|
+
* answered as it came.
|
|
477
|
+
*/
|
|
478
|
+
var offlineDataWith = (offlineData, schema) => {
|
|
479
|
+
if (schema === offlineData.schema) return offlineData;
|
|
480
|
+
const copies = sent.get(offlineData) ?? /* @__PURE__ */ new WeakMap();
|
|
481
|
+
sent.set(offlineData, copies);
|
|
482
|
+
const known = copies.get(schema);
|
|
483
|
+
if (known) return known;
|
|
484
|
+
const copy = {
|
|
485
|
+
...offlineData,
|
|
486
|
+
schema
|
|
487
|
+
};
|
|
488
|
+
copies.set(schema, copy);
|
|
489
|
+
return copy;
|
|
490
|
+
};
|
|
491
|
+
var sheets = /* @__PURE__ */ new WeakMap();
|
|
492
|
+
/**
|
|
493
|
+
* The space's stylesheet as a file — made once per style object, which the adapters hand every render until the
|
|
494
|
+
* space changes, and which a page's withheld copy of the space shares — or `undefined` when it stays in the page
|
|
495
|
+
* (`styleSheetLinkable`).
|
|
496
|
+
*/
|
|
497
|
+
var styleSheetOf = (offlineData) => {
|
|
498
|
+
const known = sheets.get(offlineData.style);
|
|
499
|
+
if (known !== void 0) return known ?? void 0;
|
|
500
|
+
if (!styleSheetLinkable(offlineData.style.cache)) {
|
|
501
|
+
sheets.set(offlineData.style, null);
|
|
502
|
+
return;
|
|
503
|
+
}
|
|
504
|
+
const css = styleSheetCss(offlineData.style.cache);
|
|
505
|
+
const hash = digest(css);
|
|
506
|
+
const sheet = {
|
|
507
|
+
css,
|
|
508
|
+
hash,
|
|
509
|
+
href: styleSheetHref(hash),
|
|
510
|
+
compressed: {}
|
|
511
|
+
};
|
|
512
|
+
sheets.set(offlineData.style, sheet);
|
|
513
|
+
return sheet;
|
|
514
|
+
};
|
|
515
|
+
var linked = /* @__PURE__ */ new WeakMap();
|
|
516
|
+
var carried = /* @__PURE__ */ new WeakMap();
|
|
517
|
+
/**
|
|
518
|
+
* The space as the page reads it — escaped JSON, safe inside a `<script>` — made once per space object rather than
|
|
519
|
+
* once per render.
|
|
520
|
+
*
|
|
521
|
+
* It is most of the payload, and the adapters hand every request the same object until the space changes, so turning
|
|
522
|
+
* it into JSON on each render was a tenth of a render's CPU spent producing the same string. Keyed weakly: a space the
|
|
523
|
+
* adapters let go of takes its string with it.
|
|
524
|
+
*
|
|
525
|
+
* `linkStyle`, the compiled stylesheet is a file the page links (`styleSheetOf`): the document names it as
|
|
526
|
+
* `style.cacheHref` and carries none of it. Without, the page carries it — a page no other request could answer the
|
|
527
|
+
* file for: a draft, a space named by a token.
|
|
528
|
+
*
|
|
529
|
+
* The hash names the text, so a page can be told where to fetch it and the answer can be kept forever.
|
|
530
|
+
*/
|
|
531
|
+
var spaceDocument = (offlineData, { linkStyle = true } = {}) => {
|
|
532
|
+
const documents = linkStyle ? linked : carried;
|
|
533
|
+
const known = documents.get(offlineData);
|
|
534
|
+
if (known) return known;
|
|
535
|
+
const sheet = linkStyle ? styleSheetOf(offlineData) : void 0;
|
|
536
|
+
const data = sheet ? {
|
|
537
|
+
...offlineData,
|
|
538
|
+
style: {
|
|
539
|
+
...offlineData.style,
|
|
540
|
+
cache: "",
|
|
541
|
+
cacheHref: sheet.href
|
|
542
|
+
}
|
|
543
|
+
} : offlineData;
|
|
544
|
+
const json = escapeJson(JSON.stringify(data));
|
|
545
|
+
const document = {
|
|
546
|
+
json,
|
|
547
|
+
hash: digest(json),
|
|
548
|
+
data
|
|
549
|
+
};
|
|
550
|
+
documents.set(offlineData, document);
|
|
551
|
+
return document;
|
|
552
|
+
};
|
|
553
|
+
/**
|
|
554
|
+
* What the page's bootstrap reads: `{ offlineData, ...rest }` as escaped JSON, byte for byte what serializing the
|
|
555
|
+
* whole object would give. The escaping replaces characters one by one, so escaping the parts and joining them is
|
|
556
|
+
* the same as escaping the whole.
|
|
557
|
+
*
|
|
558
|
+
* `apart`, the space is not in it: the page fetches it (`spaceDocumentPath`), and only what is this request's travels
|
|
559
|
+
* inline.
|
|
560
|
+
*/
|
|
561
|
+
var hydrationPayload = (offlineData, rest, { apart = false, linkStyle = true } = {}) => {
|
|
562
|
+
const serializedRest = escapeJson(JSON.stringify(rest));
|
|
563
|
+
if (offlineData === void 0 || apart) return serializedRest;
|
|
564
|
+
const separator = serializedRest === "{}" ? "" : ",";
|
|
565
|
+
return `{"offlineData":${spaceDocument(offlineData, { linkStyle }).json}${separator}${serializedRest.slice(1)}`;
|
|
566
|
+
};
|
|
567
|
+
// src/helpers/cache/serverCaches.ts
|
|
568
|
+
var sizeOfString = (value) => value.length;
|
|
569
|
+
var createServerCaches = ({ htmlTtlMs = DEFAULT_TTL_MS.html, rscTtlMs = DEFAULT_TTL_MS.rsc, htmlBytes = DEFAULT_CACHE_BYTES.html, staleMs = DEFAULT_TTL_MS.stale } = {}) => ({
|
|
570
|
+
html: htmlTtlMs > 0 ? new TtlCache(htmlTtlMs, 5e3, {
|
|
571
|
+
maxBytes: htmlBytes,
|
|
572
|
+
sizeOf: sizeOfPage,
|
|
573
|
+
staleMs
|
|
574
|
+
}) : void 0,
|
|
575
|
+
rsc: rscTtlMs > 0 ? new TtlCache(rscTtlMs, 5e3, {
|
|
576
|
+
maxBytes: DEFAULT_CACHE_BYTES.rsc,
|
|
577
|
+
sizeOf: sizeOfString
|
|
578
|
+
}) : void 0,
|
|
579
|
+
offlineData: htmlTtlMs > 0 ? new TtlCache(htmlTtlMs, 500, {
|
|
580
|
+
maxBytes: DEFAULT_CACHE_BYTES.offlineData,
|
|
581
|
+
sizeOf: (offlineData) => spaceDocument(offlineData).json.length
|
|
582
|
+
}) : void 0,
|
|
583
|
+
rendering: /* @__PURE__ */ new Map(),
|
|
584
|
+
turns: createRenderTurns()
|
|
585
|
+
});
|
|
586
|
+
var destroyServerCaches = ({ html, rsc, offlineData, rendering }) => {
|
|
587
|
+
html?.destroy();
|
|
588
|
+
rsc?.destroy();
|
|
589
|
+
offlineData?.destroy();
|
|
590
|
+
rendering.clear();
|
|
591
|
+
};
|
|
592
|
+
// src/helpers/cache/sharedCache.ts
|
|
593
|
+
/** The topic the processes of a deployment tell each other what their pages no longer hold on. */
|
|
594
|
+
var CACHE_TOPIC = "ssr.cache";
|
|
595
|
+
var LABEL = "SSR cache";
|
|
596
|
+
/** A filter as it travelled: only the fields a filter has, of the types it has them. */
|
|
597
|
+
var cacheFilterOf = (value) => {
|
|
598
|
+
if (!isRecord(value)) return {};
|
|
599
|
+
return {
|
|
600
|
+
...typeof value.spaceId === "number" ? { spaceId: value.spaceId } : {},
|
|
601
|
+
...typeof value.environment === "string" ? { environment: value.environment } : {},
|
|
602
|
+
...typeof value.hostname === "string" ? { hostname: value.hostname } : {}
|
|
603
|
+
};
|
|
604
|
+
};
|
|
605
|
+
var messageOf = (raw) => {
|
|
606
|
+
let value;
|
|
607
|
+
try {
|
|
608
|
+
value = JSON.parse(raw);
|
|
609
|
+
} catch {
|
|
610
|
+
return;
|
|
611
|
+
}
|
|
612
|
+
if (!isRecord(value) || typeof value.from !== "string") return;
|
|
613
|
+
if (value.op === "clear") return {
|
|
614
|
+
op: "clear",
|
|
615
|
+
from: value.from
|
|
616
|
+
};
|
|
617
|
+
return value.op === "invalidate" ? {
|
|
618
|
+
op: "invalidate",
|
|
619
|
+
filter: cacheFilterOf(value.filter),
|
|
620
|
+
from: value.from
|
|
621
|
+
} : void 0;
|
|
622
|
+
};
|
|
623
|
+
/**
|
|
624
|
+
* What says to every replica that pages no longer hold — and drops them from the store they share. For a process that
|
|
625
|
+
* writes a space without serving its pages (an API beside the page servers): `server.cache` does the same where it
|
|
626
|
+
* renders them. Rejects with what could not be said, so the write that called it can say the pages are stale.
|
|
627
|
+
*/
|
|
628
|
+
var createCacheInvalidator = ({ bus, store }, from = randomUUID()) => {
|
|
629
|
+
const say = async (message, filter) => {
|
|
630
|
+
await Promise.all([bus?.publish(CACHE_TOPIC, JSON.stringify(message)), store?.invalidate(filter)]);
|
|
631
|
+
};
|
|
632
|
+
return {
|
|
633
|
+
invalidate: (filter) => say({
|
|
634
|
+
op: "invalidate",
|
|
635
|
+
filter: filter ?? {},
|
|
636
|
+
from
|
|
637
|
+
}, filter),
|
|
638
|
+
clear: () => say({
|
|
639
|
+
op: "clear",
|
|
640
|
+
from
|
|
641
|
+
})
|
|
642
|
+
};
|
|
643
|
+
};
|
|
644
|
+
/**
|
|
645
|
+
* `server.cache`, reaching every replica: what this process is told it does here, says on the bus for the others, and
|
|
646
|
+
* drops from the shared store; what another says on the bus, it does here. Each process on the bus hears it, the
|
|
647
|
+
* workers of one host included — so a deployment with a bus needs no relay of its own between them.
|
|
648
|
+
*/
|
|
649
|
+
var shareCache = (cache, sharing) => {
|
|
650
|
+
const from = randomUUID();
|
|
651
|
+
const invalidator = createCacheInvalidator(sharing, from);
|
|
652
|
+
const told = (what) => (error) => {
|
|
653
|
+
serverLog.warn(LABEL, `${what} reached only this process: the other replicas keep those pages until their TTL`, error);
|
|
654
|
+
};
|
|
655
|
+
let unsubscribe;
|
|
656
|
+
const ready = sharing.bus ? sharing.bus.subscribe(CACHE_TOPIC, (raw) => {
|
|
657
|
+
const message = messageOf(raw);
|
|
658
|
+
if (!message) {
|
|
659
|
+
serverLog.warn(LABEL, `A message on ${CACHE_TOPIC} was ignored: it is not one this server sends`);
|
|
660
|
+
return;
|
|
661
|
+
}
|
|
662
|
+
if (message.from === from) return;
|
|
663
|
+
if (message.op === "clear") cache.clear();
|
|
664
|
+
else cache.invalidate(message.filter);
|
|
665
|
+
}).then((stop) => {
|
|
666
|
+
unsubscribe = stop;
|
|
667
|
+
}).catch((error) => {
|
|
668
|
+
serverLog.warn(LABEL, `Not subscribed to ${CACHE_TOPIC}: what other replicas invalidate is kept here until its TTL`, error);
|
|
669
|
+
}) : Promise.resolve();
|
|
670
|
+
return {
|
|
671
|
+
cache: {
|
|
672
|
+
invalidate: (filter) => {
|
|
673
|
+
const count = cache.invalidate(filter);
|
|
674
|
+
invalidator.invalidate(filter).catch(told("An invalidation"));
|
|
675
|
+
return count;
|
|
676
|
+
},
|
|
677
|
+
clear: () => {
|
|
678
|
+
cache.clear();
|
|
679
|
+
invalidator.clear().catch(told("Clearing the cache"));
|
|
680
|
+
},
|
|
681
|
+
get size() {
|
|
682
|
+
return cache.size;
|
|
683
|
+
}
|
|
684
|
+
},
|
|
685
|
+
ready,
|
|
686
|
+
close: async () => {
|
|
687
|
+
await ready;
|
|
688
|
+
await unsubscribe?.();
|
|
689
|
+
}
|
|
690
|
+
};
|
|
691
|
+
};
|
|
692
|
+
// src/helpers/cache/limits.ts
|
|
693
|
+
/** What the deployment's environment may say of the caches when its code says nothing. */
|
|
694
|
+
var CACHE_ENV = {
|
|
695
|
+
maxBytes: "SDK_SERVER_CACHE_MAX_BYTES",
|
|
696
|
+
storeMaxBytes: "SDK_SERVER_CACHE_STORE_MAX_BYTES"
|
|
697
|
+
};
|
|
698
|
+
var UNITS = {
|
|
699
|
+
"": 1,
|
|
700
|
+
b: 1,
|
|
701
|
+
kb: 1024,
|
|
702
|
+
mb: 1024 ** 2,
|
|
703
|
+
gb: 1024 ** 3
|
|
704
|
+
};
|
|
705
|
+
/**
|
|
706
|
+
* A size as the environment writes it — `134217728`, `128MB`, `2GB` — or nothing when it says none. Refused when it is
|
|
707
|
+
* not one, naming the variable: a typo that read as no limit would be a cache with none.
|
|
708
|
+
*/
|
|
709
|
+
var bytesFromEnvironment = (name, environment = process.env) => {
|
|
710
|
+
const raw = environment[name]?.trim();
|
|
711
|
+
if (raw === void 0 || raw === "") return;
|
|
712
|
+
const match = /^(\d+(?:\.\d+)?)\s*([kmg]?b?)$/i.exec(raw);
|
|
713
|
+
const unit = match ? UNITS[match[2].toLowerCase()] : void 0;
|
|
714
|
+
if (!match || unit === void 0 || Number(match[1]) <= 0) throw new Error(`${name} must be a size in bytes, or with a unit: 134217728, 128MB, 2GB — got "${raw}"`);
|
|
715
|
+
return Math.round(Number(match[1]) * unit);
|
|
716
|
+
};
|
|
717
|
+
/** What one process keeps of pages, and for how long past their TTL: the config, else the environment, else the default. */
|
|
718
|
+
var cacheLimitsOf = (config, environment = process.env) => ({
|
|
719
|
+
maxBytes: config.cache?.maxBytes ?? bytesFromEnvironment(CACHE_ENV.maxBytes, environment) ?? DEFAULT_CACHE_BYTES.html,
|
|
720
|
+
staleMs: config.cache?.staleMs ?? DEFAULT_TTL_MS.stale
|
|
721
|
+
});
|
|
722
|
+
// src/helpers/normalizePlugins.ts
|
|
723
|
+
var DEFAULT_PLUGIN_VERSION = "1.0.0";
|
|
724
|
+
var normalizePluginSource = (source) => ({
|
|
725
|
+
...source,
|
|
726
|
+
version: source.version ?? DEFAULT_PLUGIN_VERSION
|
|
727
|
+
});
|
|
728
|
+
var normalizePlugins = (plugins) => {
|
|
729
|
+
const out = {};
|
|
730
|
+
for (const [name, source] of Object.entries(plugins)) {
|
|
731
|
+
const normalized = normalizePluginSource(source);
|
|
732
|
+
out[`${name}@${normalized.version}`] = normalized;
|
|
733
|
+
}
|
|
734
|
+
return out;
|
|
735
|
+
};
|
|
736
|
+
// src/helpers/reportReactBuild.ts
|
|
737
|
+
var reported = false;
|
|
738
|
+
/**
|
|
739
|
+
* Says, once per process, that a production server is rendering with React's development build.
|
|
740
|
+
*
|
|
741
|
+
* React picks its build from `NODE_ENV` when it is first imported, not from anything a server is configured with, so
|
|
742
|
+
* `devMode: false` without `NODE_ENV=production` renders every page with the development build — measured at about 40%
|
|
743
|
+
* fewer pages a second. An `error` because it is the only level a production server shows, and a deployment that
|
|
744
|
+
* never sees this line never learns why it needs twice the CPU.
|
|
745
|
+
*/
|
|
746
|
+
var reportReactBuild = (devMode, nodeEnv = process.env.NODE_ENV) => {
|
|
747
|
+
if (reported || devMode || nodeEnv === "production") return;
|
|
748
|
+
reported = true;
|
|
749
|
+
serverLog.error("server", `NODE_ENV is ${nodeEnv === void 0 ? "unset" : `"${nodeEnv}"`}: React renders with its development build. Start the process with NODE_ENV=production.`);
|
|
750
|
+
};
|
|
751
|
+
// src/helpers/offlineDataLoader.ts
|
|
752
|
+
/**
|
|
753
|
+
* One read of the space per request, however many things ask for it.
|
|
754
|
+
*
|
|
755
|
+
* The page render and the RSC read both need the schema and are deliberately started in parallel, so neither can
|
|
756
|
+
* hand its result to the other. Sharing the promise is what makes that safe: whichever asks first begins the read
|
|
757
|
+
* and the other joins it. It holds the promise, not the value — there is no cache here and nothing to invalidate,
|
|
758
|
+
* because it lives exactly as long as the request that made it.
|
|
759
|
+
*/
|
|
760
|
+
var createOfflineDataLoader = (read) => {
|
|
761
|
+
let pending;
|
|
762
|
+
return () => pending ??= read();
|
|
763
|
+
};
|
|
764
|
+
// src/modules/ssr/scriptPolicy.ts
|
|
765
|
+
/** Where a browser reports what the page's script policy would have refused (`cspReportStage`). */
|
|
766
|
+
var CSP_REPORT_PATH = "/_plitzi/csp-report";
|
|
767
|
+
/**
|
|
768
|
+
* The nonce of one render of a page: what its template writes on each of its own scripts (`nonce="…"`), and what its
|
|
769
|
+
* script policy names. A nonce and not the scripts' hashes, because the page is made of modules: what a script imports
|
|
770
|
+
* (`import()`, the SDK and every plugin) is trusted by `'strict-dynamic'` through the importing script's nonce, and a
|
|
771
|
+
* hash passes nothing on to the modules it loads.
|
|
772
|
+
*
|
|
773
|
+
* Kept with the page while it is cached, and made anew each time it is rendered again: a cached page is sent many
|
|
774
|
+
* times, compressed once, and its bytes cannot change per response. A script someone wrote into the page (a raw HTML
|
|
775
|
+
* block) carries none — the nonce is not in the document until the page is rendered, and is never one they could know.
|
|
776
|
+
*/
|
|
777
|
+
var newScriptNonce = () => randomBytes(16).toString("base64");
|
|
778
|
+
/** What a page's template is given of its script policy: the render's nonce, and the policy said on `<html>`. */
|
|
779
|
+
var scriptTemplateParams = (config, deployment) => {
|
|
780
|
+
const mode = scriptPolicyMode(config, deployment);
|
|
781
|
+
return mode ? {
|
|
782
|
+
nonce: newScriptNonce(),
|
|
783
|
+
scriptPolicy: mode
|
|
784
|
+
} : {};
|
|
785
|
+
};
|
|
786
|
+
/** The page's script policy on a host: the deployment's for its domain, else the server's — none for `off`. */
|
|
787
|
+
var scriptPolicyMode = (config, deployment) => {
|
|
788
|
+
const chosen = deployment?.security?.scriptPolicy ?? config.scriptPolicy ?? "report-only";
|
|
789
|
+
return chosen === "off" || chosen === false ? void 0 : chosen;
|
|
790
|
+
};
|
|
791
|
+
/**
|
|
792
|
+
* What a page rendered with `nonce` is held to: its own scripts, what they load (`'strict-dynamic'`), and no plugin
|
|
793
|
+
* object nor `<base>` that would move where the page's scripts come from. `'unsafe-inline'` and `https:` are there for
|
|
794
|
+
* a browser that knows neither nonces nor `'strict-dynamic'`, and one that does ignores both.
|
|
795
|
+
*/
|
|
796
|
+
var scriptDirectives = (nonce) => [
|
|
797
|
+
`script-src 'nonce-${nonce}' 'strict-dynamic' 'unsafe-inline' https:`,
|
|
798
|
+
"object-src 'none'",
|
|
799
|
+
"base-uri 'none'"
|
|
800
|
+
];
|
|
801
|
+
/** Markup written into the page only through the SDK's named policies (`TRUSTED_TYPES_POLICIES`). */
|
|
802
|
+
var trustedTypesDirectives = () => ["require-trusted-types-for 'script'", `trusted-types ${TRUSTED_TYPES_POLICIES.join(" ")} 'allow-duplicates'`];
|
|
803
|
+
var REPORT_TO = `report-uri ${CSP_REPORT_PATH}`;
|
|
804
|
+
/**
|
|
805
|
+
* A page's policies, as the two headers carry them: what is enforced — the script policy when it is, beside who may
|
|
806
|
+
* frame the page (`frameAncestors`, the one header carrying both, since a second would only narrow the first) — and
|
|
807
|
+
* what is only reported: the script policy while it is reported, and Trusted Types (`trustedTypes`) until it is
|
|
808
|
+
* enforced too.
|
|
809
|
+
*/
|
|
810
|
+
var pagePolicies = ({ nonce, mode, trustedTypes, frameAncestors }) => {
|
|
811
|
+
const enforced = [...frameAncestors ? [frameAncestors] : [], ...mode === "enforce" && nonce ? [...scriptDirectives(nonce), REPORT_TO] : []];
|
|
812
|
+
const reported = [...mode === "report-only" && nonce ? scriptDirectives(nonce) : [], ...mode && trustedTypes ? trustedTypesDirectives() : []];
|
|
813
|
+
return {
|
|
814
|
+
...enforced.length > 0 ? { enforced: enforced.join("; ") } : {},
|
|
815
|
+
...reported.length > 0 ? { reportOnly: [...reported, REPORT_TO].join("; ") } : {}
|
|
816
|
+
};
|
|
817
|
+
};
|
|
818
|
+
/** The page's policies on its response (`pagePolicies`), for the host it was asked on; none without a nonce. */
|
|
819
|
+
var sendScriptPolicy = (res, config, nonce, deployment) => {
|
|
820
|
+
const { enforced, reportOnly } = pagePolicies({
|
|
821
|
+
nonce,
|
|
822
|
+
mode: scriptPolicyMode(config, deployment),
|
|
823
|
+
trustedTypes: config.trustedTypes !== false,
|
|
824
|
+
frameAncestors: frameAncestorsOf(config, deployment)
|
|
825
|
+
});
|
|
826
|
+
if (enforced) res.setHeader("Content-Security-Policy", enforced);
|
|
827
|
+
if (reportOnly) res.setHeader("Content-Security-Policy-Report-Only", reportOnly);
|
|
828
|
+
};
|
|
829
|
+
// src/modules/fonts/googleFonts.ts
|
|
830
|
+
/** Where a page's Google families are served from, on the page server's own origin. */
|
|
831
|
+
var GOOGLE_FONTS_PATH = "/_plitzi/fonts/google";
|
|
832
|
+
var GOOGLE_CSS_ORIGIN = "https://fonts.googleapis.com";
|
|
833
|
+
var GOOGLE_FILE_ORIGIN = "https://fonts.gstatic.com";
|
|
834
|
+
/**
|
|
835
|
+
* Google answers each browser the formats it reads, by its `User-Agent`: one that names no modern browser is answered
|
|
836
|
+
* `.ttf` files without `unicode-range`, every face of every script whole. A current one gets the WOFF2 subsets.
|
|
837
|
+
*/
|
|
838
|
+
var MODERN_BROWSER = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36";
|
|
839
|
+
/**
|
|
840
|
+
* A file of Google's, as its stylesheet names it: `/s/<family>/v<n>/<name>.woff2`, versioned and so never changing — and
|
|
841
|
+
* `<name>.<subset>.woff2` for a family split into numbered subsets, as every Japanese, Chinese and Korean one is.
|
|
842
|
+
*/
|
|
843
|
+
var FILE_PATH = /^\/s\/[a-z0-9]+\/v\d+\/[A-Za-z0-9_-]+(?:\.\d{1,4})?\.(woff2|woff|ttf)$/;
|
|
844
|
+
var FILE_TYPES = {
|
|
845
|
+
woff2: "font/woff2",
|
|
846
|
+
woff: "font/woff",
|
|
847
|
+
ttf: "font/ttf"
|
|
848
|
+
};
|
|
849
|
+
/**
|
|
850
|
+
* A family Google serves only built on request is named at `/l/font?kit=…&skey=…&v=v<n>` — the same file for the same
|
|
851
|
+
* three, and so kept like the others. Its type is the one Google answers it with.
|
|
852
|
+
*/
|
|
853
|
+
var DYNAMIC_PATH = "/l/font";
|
|
854
|
+
var DYNAMIC_PARAMS = {
|
|
855
|
+
kit: /^[A-Za-z0-9_-]{1,512}$/,
|
|
856
|
+
skey: /^[a-f0-9]{1,64}$/,
|
|
857
|
+
v: /^v\d{1,4}$/
|
|
858
|
+
};
|
|
859
|
+
/** A file of Google's this mirror serves: where it is asked, under what it is kept, and its type when the path says. */
|
|
860
|
+
var fileOf = (rest, search) => {
|
|
861
|
+
const format = FILE_PATH.exec(rest)?.[1];
|
|
862
|
+
if (format !== void 0) return {
|
|
863
|
+
upstream: `${GOOGLE_FILE_ORIGIN}${rest}`,
|
|
864
|
+
key: rest,
|
|
865
|
+
type: FILE_TYPES[format]
|
|
866
|
+
};
|
|
867
|
+
if (rest !== DYNAMIC_PATH) return;
|
|
868
|
+
const params = new URLSearchParams(search);
|
|
869
|
+
if ([...params.keys()].length !== Object.keys(DYNAMIC_PARAMS).length || Object.entries(DYNAMIC_PARAMS).some(([name, valid]) => params.getAll(name).length !== 1 || !valid.test(params.get(name) ?? ""))) return;
|
|
870
|
+
const query = Object.keys(DYNAMIC_PARAMS).map((name) => `${name}=${params.get(name) ?? ""}`).join("&");
|
|
871
|
+
return {
|
|
872
|
+
upstream: `${GOOGLE_FILE_ORIGIN}${DYNAMIC_PATH}?${query}`,
|
|
873
|
+
key: `${DYNAMIC_PATH}?${query}`
|
|
874
|
+
};
|
|
875
|
+
};
|
|
876
|
+
/** What Google said a file is, when it said a font: anything else is served as the WOFF2 it asks for. */
|
|
877
|
+
var fontTypeOf = (response) => {
|
|
878
|
+
const said = response.headers.get("content-type")?.split(";")[0]?.trim() ?? "";
|
|
879
|
+
return said.startsWith("font/") ? said : "font/woff2";
|
|
880
|
+
};
|
|
881
|
+
/** What one request may name: the page's families (a manifest has a handful), and the one `display` css2 takes. */
|
|
882
|
+
var MAX_FAMILIES = 24;
|
|
883
|
+
var MAX_FAMILY_LENGTH = 200;
|
|
884
|
+
var DISPLAYS = /* @__PURE__ */ new Set([
|
|
885
|
+
"auto",
|
|
886
|
+
"block",
|
|
887
|
+
"swap",
|
|
888
|
+
"fallback",
|
|
889
|
+
"optional"
|
|
890
|
+
]);
|
|
891
|
+
/** Google's own: a stylesheet for a day, which is as long as it keeps one; a file, for good. */
|
|
892
|
+
var CSS_TTL_MS = 864e5;
|
|
893
|
+
var FILE_TTL_MS = 2592e6;
|
|
894
|
+
var CSS_CACHE_CONTROL = "public, max-age=86400, stale-while-revalidate=604800";
|
|
895
|
+
var FILE_CACHE_CONTROL = "public, max-age=31536000, immutable";
|
|
896
|
+
var SWEEP_MS = 36e5;
|
|
897
|
+
/**
|
|
898
|
+
* Google splits a family in subsets, one `@font-face` each, and a Japanese or Chinese family is a hundred subsets per
|
|
899
|
+
* weight: three weights of one are over 300 KB, and a page with a CJK family beside two others asked for 460 KB — over
|
|
900
|
+
* the 256 KB this was, which sent every visitor of it to Google. Two megabytes hold several CJK families at once.
|
|
901
|
+
*/
|
|
902
|
+
var MAX_CSS_BYTES = 2097152;
|
|
903
|
+
var MAX_FILE_BYTES = 2097152;
|
|
904
|
+
/** The faces every space of this server uses, kept in this process — a dozen families' subsets fit many times over. */
|
|
905
|
+
var DEFAULT_GOOGLE_FONTS_MAX_BYTES = 33554432;
|
|
906
|
+
/**
|
|
907
|
+
* The query a stylesheet is asked with, said one way: its families, in the order they came, and its `display` — or
|
|
908
|
+
* nothing, for a request that is not one a page writes (a `text` subset, a family past the bound).
|
|
909
|
+
*/
|
|
910
|
+
var css2Query = (search) => {
|
|
911
|
+
const params = new URLSearchParams(search);
|
|
912
|
+
const families = params.getAll("family");
|
|
913
|
+
if (families.length === 0 || families.length > MAX_FAMILIES || families.some((family) => family.length === 0 || family.length > MAX_FAMILY_LENGTH)) return;
|
|
914
|
+
const display = params.get("display");
|
|
915
|
+
if (display !== null && !DISPLAYS.has(display)) return;
|
|
916
|
+
if ([...params.keys()].some((key) => key !== "family" && key !== "display")) return;
|
|
917
|
+
const canonical = new URLSearchParams();
|
|
918
|
+
families.forEach((family) => {
|
|
919
|
+
canonical.append("family", family);
|
|
920
|
+
});
|
|
921
|
+
if (display !== null) canonical.set("display", display);
|
|
922
|
+
return canonical.toString().replace(/%3A/g, ":").replace(/%40/g, "@").replace(/%3B/g, ";").replace(/%2C/g, ",");
|
|
923
|
+
};
|
|
924
|
+
/** One request upstream per key at a time: the pages that ask while it is in flight wait on the same answer. */
|
|
925
|
+
var singleFlight = () => {
|
|
926
|
+
const asking = /* @__PURE__ */ new Map();
|
|
927
|
+
return (key, ask) => {
|
|
928
|
+
const known = asking.get(key);
|
|
929
|
+
if (known) return known;
|
|
930
|
+
const asked = ask().finally(() => asking.delete(key));
|
|
931
|
+
asking.set(key, asked);
|
|
932
|
+
return asked;
|
|
933
|
+
};
|
|
934
|
+
};
|
|
935
|
+
/** Google's stylesheet, its files addressed where this server serves them. */
|
|
936
|
+
var rewritten = (css) => css.replaceAll(`${GOOGLE_FILE_ORIGIN}/`, `${GOOGLE_FONTS_PATH}/`);
|
|
937
|
+
/**
|
|
938
|
+
* A page's Google families, served from the page server's own origin rather than Google's.
|
|
939
|
+
*
|
|
940
|
+
* A stylesheet in the head is render-blocking, and Google's are on two origins of their own — the CSS and the files it
|
|
941
|
+
* names — each a DNS lookup, a TLS handshake and a connection the visitor opens before the text is drawn in its face.
|
|
942
|
+
* Served here, they ride the connection the page came on. And the visitor's address is not handed to a third party for
|
|
943
|
+
* a typeface, which in the EU is a question of its own.
|
|
944
|
+
*
|
|
945
|
+
* Asked of Google once per stylesheet and file, kept in this process within `maxBytes`, joined while in flight. Google
|
|
946
|
+
* unreachable is not the page's problem: the browser is sent to Google itself (a redirect), and the server says why.
|
|
947
|
+
*/
|
|
948
|
+
var createGoogleFontsMirror = ({ fetch: base = globalThis.fetch, maxBytes = DEFAULT_GOOGLE_FONTS_MAX_BYTES } = {}) => {
|
|
949
|
+
const stylesheets = new TtlCache(CSS_TTL_MS, 500, {
|
|
950
|
+
maxBytes: Math.max(4 * MAX_CSS_BYTES, Math.floor(maxBytes / 16)),
|
|
951
|
+
sizeOf: (css) => Buffer.byteLength(css),
|
|
952
|
+
sweepIntervalMs: SWEEP_MS
|
|
953
|
+
});
|
|
954
|
+
const files = new TtlCache(FILE_TTL_MS, 5e3, {
|
|
955
|
+
maxBytes,
|
|
956
|
+
sizeOf: (file) => file.bytes.byteLength,
|
|
957
|
+
sweepIntervalMs: SWEEP_MS
|
|
958
|
+
});
|
|
959
|
+
const askingCss = singleFlight();
|
|
960
|
+
const askingFile = singleFlight();
|
|
961
|
+
const fetched = async (url, maxSize) => {
|
|
962
|
+
const response = await base(url, {
|
|
963
|
+
headers: { "User-Agent": MODERN_BROWSER },
|
|
964
|
+
redirect: "error"
|
|
965
|
+
});
|
|
966
|
+
if (!response.ok) throw new Error(`${url} answered ${String(response.status)}`);
|
|
967
|
+
const declared = Number(response.headers.get("content-length") ?? "");
|
|
968
|
+
if (Number.isFinite(declared) && declared > maxSize) throw new Error(`${url} is larger than ${String(maxSize)} bytes`);
|
|
969
|
+
return response;
|
|
970
|
+
};
|
|
971
|
+
const sentToGoogle = (url, error) => {
|
|
972
|
+
serverLog.warn("FONTS", `Google Fonts could not be reached; the browser is sent to ${url}`, error);
|
|
973
|
+
return {
|
|
974
|
+
status: 307,
|
|
975
|
+
headers: {
|
|
976
|
+
Location: url,
|
|
977
|
+
"Cache-Control": "no-store"
|
|
978
|
+
},
|
|
979
|
+
body: ""
|
|
980
|
+
};
|
|
981
|
+
};
|
|
982
|
+
return async ({ path, search }) => {
|
|
983
|
+
const rest = path.slice(21);
|
|
984
|
+
if (rest === "/css2") {
|
|
985
|
+
const query = css2Query(search);
|
|
986
|
+
if (query === void 0) return {
|
|
987
|
+
status: 400,
|
|
988
|
+
headers: {},
|
|
989
|
+
body: "Not a stylesheet of Google Fonts a page asks for"
|
|
990
|
+
};
|
|
991
|
+
const upstream = `${GOOGLE_CSS_ORIGIN}/css2?${query}`;
|
|
992
|
+
try {
|
|
993
|
+
const css = stylesheets.get(query) ?? await askingCss(query, async () => {
|
|
994
|
+
const text = await (await fetched(upstream, MAX_CSS_BYTES)).text();
|
|
995
|
+
if (Buffer.byteLength(text) > MAX_CSS_BYTES) throw new Error(`${upstream} is larger than ${String(MAX_CSS_BYTES)} bytes`);
|
|
996
|
+
const served = rewritten(text);
|
|
997
|
+
stylesheets.set(query, served);
|
|
998
|
+
return served;
|
|
999
|
+
});
|
|
1000
|
+
return {
|
|
1001
|
+
status: 200,
|
|
1002
|
+
headers: {
|
|
1003
|
+
"Content-Type": "text/css; charset=utf-8",
|
|
1004
|
+
"Cache-Control": CSS_CACHE_CONTROL
|
|
1005
|
+
},
|
|
1006
|
+
body: css
|
|
1007
|
+
};
|
|
1008
|
+
} catch (error) {
|
|
1009
|
+
return sentToGoogle(upstream, error);
|
|
1010
|
+
}
|
|
1011
|
+
}
|
|
1012
|
+
const asked = fileOf(rest, search);
|
|
1013
|
+
if (asked === void 0) return {
|
|
1014
|
+
status: 404,
|
|
1015
|
+
headers: {},
|
|
1016
|
+
body: "Not found"
|
|
1017
|
+
};
|
|
1018
|
+
const { upstream, key } = asked;
|
|
1019
|
+
try {
|
|
1020
|
+
const file = files.get(key) ?? await askingFile(key, async () => {
|
|
1021
|
+
const response = await fetched(upstream, MAX_FILE_BYTES);
|
|
1022
|
+
const bytes = Buffer.from(await response.arrayBuffer());
|
|
1023
|
+
if (bytes.byteLength > MAX_FILE_BYTES) throw new Error(`${upstream} is larger than ${String(MAX_FILE_BYTES)} bytes`);
|
|
1024
|
+
const kept = {
|
|
1025
|
+
bytes,
|
|
1026
|
+
type: asked.type ?? fontTypeOf(response)
|
|
1027
|
+
};
|
|
1028
|
+
files.set(key, kept);
|
|
1029
|
+
return kept;
|
|
1030
|
+
});
|
|
1031
|
+
return {
|
|
1032
|
+
status: 200,
|
|
1033
|
+
headers: {
|
|
1034
|
+
"Content-Type": file.type,
|
|
1035
|
+
"Cache-Control": FILE_CACHE_CONTROL,
|
|
1036
|
+
"Access-Control-Allow-Origin": "*",
|
|
1037
|
+
"Cross-Origin-Resource-Policy": "cross-origin"
|
|
1038
|
+
},
|
|
1039
|
+
body: file.bytes
|
|
1040
|
+
};
|
|
1041
|
+
} catch (error) {
|
|
1042
|
+
return sentToGoogle(upstream, error);
|
|
1043
|
+
}
|
|
1044
|
+
};
|
|
1045
|
+
};
|
|
1046
|
+
// src/core/http/stages/googleFonts.ts
|
|
1047
|
+
/** Where this server's pages ask for their Google families — its own mirror, unless `fonts.google` is `false`. */
|
|
1048
|
+
var googleFontsUrlOf = (config) => config.fonts?.google === false ? void 0 : GOOGLE_FONTS_PATH;
|
|
1049
|
+
/** One mirror per configuration, made on the first request: its cache is the process's, whatever asks. */
|
|
1050
|
+
var mirrors = /* @__PURE__ */ new WeakMap();
|
|
1051
|
+
var DEFAULT_CONFIG = {};
|
|
1052
|
+
var mirrorFor = (google) => {
|
|
1053
|
+
const key = google ?? DEFAULT_CONFIG;
|
|
1054
|
+
const known = mirrors.get(key);
|
|
1055
|
+
if (known) return known;
|
|
1056
|
+
const made = createGoogleFontsMirror(google?.maxBytes === void 0 ? {} : { maxBytes: google.maxBytes });
|
|
1057
|
+
mirrors.set(key, made);
|
|
1058
|
+
return made;
|
|
1059
|
+
};
|
|
1060
|
+
/** `/_plitzi/fonts/google/css2?family=…` and the files it names — see `SSRFontsConfig.google`. */
|
|
1061
|
+
var googleFontsStage = async (ctx) => {
|
|
1062
|
+
const google = ctx.config.fonts?.google;
|
|
1063
|
+
if (google === false || !ctx.req.path.startsWith(`/_plitzi/fonts/google/`)) return false;
|
|
1064
|
+
if (ctx.req.method !== "GET" && ctx.req.method !== "HEAD") {
|
|
1065
|
+
ctx.res.setStatus(405);
|
|
1066
|
+
ctx.res.setHeader("Allow", "GET, HEAD");
|
|
1067
|
+
ctx.res.send("Method not allowed");
|
|
1068
|
+
return true;
|
|
1069
|
+
}
|
|
1070
|
+
const answer = await mirrorFor(google)({
|
|
1071
|
+
path: ctx.req.path,
|
|
1072
|
+
query: ctx.req.query,
|
|
1073
|
+
search: ctx.req.search
|
|
1074
|
+
});
|
|
1075
|
+
ctx.res.setStatus(answer.status);
|
|
1076
|
+
for (const [name, value] of Object.entries(answer.headers)) ctx.res.setHeader(name, value);
|
|
1077
|
+
ctx.res.send(answer.body);
|
|
1078
|
+
return true;
|
|
1079
|
+
};
|
|
1080
|
+
// src/helpers/buildServerInfo.ts
|
|
1081
|
+
var getEnvironment = (env = "production", server) => {
|
|
1082
|
+
switch (env) {
|
|
1083
|
+
case "production": return server;
|
|
1084
|
+
case "staging": return {
|
|
1085
|
+
apiServer: "https://api-stg.plitzi.com",
|
|
1086
|
+
ssrServer: "https://ssr-stg.plitzi.com",
|
|
1087
|
+
serverUrl: "https://server-stg.plitzi.com",
|
|
1088
|
+
websocketServer: "wss://server-stg.plitzi.com",
|
|
1089
|
+
subscriptionServer: "wss://server-stg.plitzi.com/subscriptions",
|
|
1090
|
+
...server
|
|
1091
|
+
};
|
|
1092
|
+
case "development": return {
|
|
1093
|
+
apiServer: "https://api-dev.plitzi.com",
|
|
1094
|
+
ssrServer: "https://ssr-dev.plitzi.com",
|
|
1095
|
+
serverUrl: "https://server-dev.plitzi.com",
|
|
1096
|
+
websocketServer: "wss://server-dev.plitzi.com",
|
|
1097
|
+
subscriptionServer: "wss://server-dev.plitzi.com/subscriptions",
|
|
1098
|
+
...server
|
|
1099
|
+
};
|
|
1100
|
+
default: return {
|
|
1101
|
+
apiServer: "https://api.plitzi.local",
|
|
1102
|
+
ssrServer: "https://ssr.plitzi.local",
|
|
1103
|
+
serverUrl: "https://server.plitzi.local",
|
|
1104
|
+
websocketServer: "wss://server.plitzi.local",
|
|
1105
|
+
subscriptionServer: "wss://server.plitzi.local/subscriptions",
|
|
1106
|
+
...server
|
|
1107
|
+
};
|
|
1108
|
+
}
|
|
1109
|
+
};
|
|
1110
|
+
/**
|
|
1111
|
+
* The endpoints, the session and the location this render happens at.
|
|
1112
|
+
*
|
|
1113
|
+
* Synchronous, and takes the RSC bootstrap already resolved rather than resolving it: the only async thing here was
|
|
1114
|
+
* ever the `getRscData` call, so the caller starting that read is also what decides whether it happens at all.
|
|
1115
|
+
*/
|
|
1116
|
+
var buildServerInfo = (req, config, ssr) => {
|
|
1117
|
+
const accessToken = req.query["access-token"];
|
|
1118
|
+
const origin = requestOrigin(req) || `${req.protocol}://${req.hostname}`;
|
|
1119
|
+
const host = origin.slice(`${req.protocol}://`.length);
|
|
1120
|
+
const user = req.ctx.user;
|
|
1121
|
+
const { pageAuth } = config;
|
|
1122
|
+
const googleFontsUrl = googleFontsUrlOf(config);
|
|
1123
|
+
const scriptPolicy = scriptPolicyMode(config, req.ctx.spaceDeployment);
|
|
1124
|
+
return getEnvironment(config.environment, {
|
|
1125
|
+
basePath: "/",
|
|
1126
|
+
requestUrl: req.url || "/",
|
|
1127
|
+
origin,
|
|
1128
|
+
/**
|
|
1129
|
+
* Complete enough to be the same object a browser hands the SDK, `origin` included.
|
|
1130
|
+
*
|
|
1131
|
+
* It used to carry the hostname and the path only, which reads as a location right up until something needs to
|
|
1132
|
+
* name THIS page from the server: a sign-in link that sends somebody back where they were had nothing to build
|
|
1133
|
+
* an absolute URL out of, so a space had to name its own address in a per-environment variable instead.
|
|
1134
|
+
*/
|
|
1135
|
+
location: {
|
|
1136
|
+
origin,
|
|
1137
|
+
protocol: `${req.protocol}:`,
|
|
1138
|
+
host,
|
|
1139
|
+
hostname: req.hostname,
|
|
1140
|
+
pathname: req.path || "/",
|
|
1141
|
+
search: req.search
|
|
1142
|
+
},
|
|
1143
|
+
authenticated: !!user,
|
|
1144
|
+
skipAuth: !!accessToken,
|
|
1145
|
+
user: user ? {
|
|
1146
|
+
details: {
|
|
1147
|
+
id: user.id,
|
|
1148
|
+
username: user.username,
|
|
1149
|
+
email: user.email,
|
|
1150
|
+
verified: user.verified,
|
|
1151
|
+
permissions: user.permissions,
|
|
1152
|
+
roles: user.roles
|
|
1153
|
+
},
|
|
1154
|
+
accessToken: user.token,
|
|
1155
|
+
expiresAt: user.expiresAt
|
|
1156
|
+
} : void 0,
|
|
1157
|
+
auth: pageAuth ? {
|
|
1158
|
+
...pageAuth,
|
|
1159
|
+
sessionHintCookie: sessionHintCookieName(sessionCookieParams(req, config.authCookie))
|
|
1160
|
+
} : void 0,
|
|
1161
|
+
...config.fonts?.baseUrl ? { fontsBaseUrl: config.fonts.baseUrl } : {},
|
|
1162
|
+
...googleFontsUrl === void 0 ? {} : { googleFontsUrl },
|
|
1163
|
+
...scriptPolicy === void 0 ? {} : { scriptPolicy },
|
|
1164
|
+
ssr
|
|
1165
|
+
});
|
|
1166
|
+
};
|
|
1167
|
+
// src/helpers/resolveDebugMode.ts
|
|
1168
|
+
/**
|
|
1169
|
+
* Whether a render may expose debugging: the panel, element ids in the markup, the store.
|
|
1170
|
+
*
|
|
1171
|
+
* An SSR page loads the same SDK a client-rendered one does, so it follows the same rule: the page's `debugMode`
|
|
1172
|
+
* authorizes it (`devMode` when the server did not say otherwise), and the 'plitzi_debug' cookie is only the
|
|
1173
|
+
* visitor's preference within that — it exists so the SSR render matches what the client hydrates with. Being
|
|
1174
|
+
* client-owned, the cookie can turn debugging off, never on: otherwise any visitor of a published site could set it
|
|
1175
|
+
* and get the debug render.
|
|
1176
|
+
*/
|
|
1177
|
+
var resolveDebugMode = (authorized, debugCookie) => Boolean(authorized) && debugCookie !== "false";
|
|
1178
|
+
// src/helpers/escapeHtml.ts
|
|
1179
|
+
/** Text set inside HTML as text: never markup, whatever it holds. */
|
|
1180
|
+
var escapeHtml = (value) => value.replace(/[&<>"']/gu, (character) => {
|
|
1181
|
+
switch (character) {
|
|
1182
|
+
case "&": return "&";
|
|
1183
|
+
case "<": return "<";
|
|
1184
|
+
case ">": return ">";
|
|
1185
|
+
case "\"": return """;
|
|
1186
|
+
default: return "'";
|
|
1187
|
+
}
|
|
1188
|
+
});
|
|
1189
|
+
// src/helpers/metrics.ts
|
|
1190
|
+
var RequestMetrics = class {
|
|
1191
|
+
start;
|
|
1192
|
+
phases = [];
|
|
1193
|
+
/** `before`: what the request spent before the render began — its middlewares, the metering (`ctx.timings`). */
|
|
1194
|
+
constructor(before = []) {
|
|
1195
|
+
this.start = performance.now();
|
|
1196
|
+
this.phases.push(...before);
|
|
1197
|
+
}
|
|
1198
|
+
async measure(name, fn) {
|
|
1199
|
+
const t = performance.now();
|
|
1200
|
+
const result = await Promise.resolve(fn());
|
|
1201
|
+
this.phases.push({
|
|
1202
|
+
name,
|
|
1203
|
+
dur: Math.round(performance.now() - t)
|
|
1204
|
+
});
|
|
1205
|
+
return result;
|
|
1206
|
+
}
|
|
1207
|
+
/** Formats as Server-Timing header value. */
|
|
1208
|
+
toServerTimingHeader() {
|
|
1209
|
+
const total = Math.round(performance.now() - this.start);
|
|
1210
|
+
return [...this.phases.map((p) => `${p.name};dur=${p.dur}`), `total;dur=${total}`].join(", ");
|
|
1211
|
+
}
|
|
1212
|
+
record(name, dur) {
|
|
1213
|
+
this.phases.push({
|
|
1214
|
+
name,
|
|
1215
|
+
dur
|
|
1216
|
+
});
|
|
1217
|
+
}
|
|
1218
|
+
/** Logs a one-line summary at `debug`. */
|
|
1219
|
+
log(label) {
|
|
1220
|
+
const total = Math.round(performance.now() - this.start);
|
|
1221
|
+
const parts = this.phases.map((p) => `${p.name}=${p.dur}ms`).join(" ");
|
|
1222
|
+
serverLog.debug("SSR", `${label} — ${parts} | total=${total}ms`);
|
|
1223
|
+
}
|
|
1224
|
+
};
|
|
1225
|
+
// src/adapters/cloudAdapters.ts
|
|
1226
|
+
/**
|
|
1227
|
+
* A space fetched from Plitzi, for a server that is not Plitzi's.
|
|
1228
|
+
*
|
|
1229
|
+
* This is the missing half of self-hosting: `createJsonAdapters` serves a space somebody exported by hand, which
|
|
1230
|
+
* goes stale the moment it is edited, and everything else meant standing up a database. Here the space stays in
|
|
1231
|
+
* the builder — published, versioned, edited by whoever normally edits it — and this deployment reads it over the
|
|
1232
|
+
* same GraphQL query the browser-rendered SDK uses, with the same space key. What is served is the deployment's
|
|
1233
|
+
* own: its own domain, its own auth, its own actions, its own logs.
|
|
1234
|
+
*
|
|
1235
|
+
* **Plitzi is never in the critical path of a page.** A version is fetched once and then served from cache; the
|
|
1236
|
+
* live document refreshes behind the request rather than in front of it, and a refresh that fails leaves the last
|
|
1237
|
+
* good copy serving. A self-hosted site does not go down because somebody else's API did.
|
|
1238
|
+
*/
|
|
1239
|
+
/**
|
|
1240
|
+
* Plitzi's own server role, which serves GraphQL at its root — no `/graphql` path, exactly as the browser SDK
|
|
1241
|
+
* addresses it. Production is the default because production is where a self-hosted deployment reads from; a
|
|
1242
|
+
* staging Plitzi is the exception and says so.
|
|
1243
|
+
*/
|
|
1244
|
+
var PLITZI_SERVER_URL = "https://server.plitzi.com";
|
|
1245
|
+
/**
|
|
1246
|
+
* The one query. Written out rather than imported from the shared package's `gql` document because this runs in a
|
|
1247
|
+
* server with no Apollo in it: the wire format is a string, and a string is what a `fetch` needs.
|
|
1248
|
+
*/
|
|
1249
|
+
var SPACE_QUERY = `query InitQuery($environment: String!, $revision: Int) {
|
|
1250
|
+
Space(environment: $environment, revision: $revision) {
|
|
1251
|
+
schema {
|
|
1252
|
+
settings
|
|
1253
|
+
rsc
|
|
1254
|
+
flat { id definition { label type initialState styleSelectors bindings interactions parentId rootId items runtime loadStrategy flag { name is } anchor } attributes }
|
|
1255
|
+
pages
|
|
1256
|
+
components
|
|
1257
|
+
flags
|
|
1258
|
+
pageFolders { id name slug parentId }
|
|
1259
|
+
variables { name type value subValues { when value } }
|
|
1260
|
+
}
|
|
1261
|
+
plugins { type resource settings }
|
|
1262
|
+
style { variables cache }
|
|
1263
|
+
}
|
|
1264
|
+
}`;
|
|
1265
|
+
/**
|
|
1266
|
+
* Which revision of an environment is current.
|
|
1267
|
+
*
|
|
1268
|
+
* A separate, tiny query on purpose: in latest mode this is what runs on a timer, and asking it is orders of
|
|
1269
|
+
* magnitude cheaper — for this deployment and for Plitzi — than pulling a whole space down to discover it did not
|
|
1270
|
+
* change. The space itself is fetched only when this answer moves.
|
|
1271
|
+
*/
|
|
1272
|
+
var LATEST_REVISION_QUERY = `query SpaceLatestRevisionQuery($environment: String!) {
|
|
1273
|
+
SpaceLatestRevision(environment: $environment) {
|
|
1274
|
+
snapshot { revision }
|
|
1275
|
+
flagsHash
|
|
1276
|
+
}
|
|
1277
|
+
}`;
|
|
1278
|
+
/**
|
|
1279
|
+
* The environment's feature flags. Asked only when the probe's `flagsHash` moved: flags change apart from revisions —
|
|
1280
|
+
* one set per environment, shared by every revision it serves — so they are fetched and kept on their own, and a flag
|
|
1281
|
+
* turned in production costs this deployment a few hundred bytes rather than the space again.
|
|
1282
|
+
*/
|
|
1283
|
+
var FLAGS_QUERY = `query SpaceFlagsQuery($environment: String!) {
|
|
1284
|
+
SpaceFlags(environment: $environment) { flags hash }
|
|
1285
|
+
}`;
|
|
1286
|
+
/** What the shared cache holds under a flags key — written by this module, but read back from outside the process. */
|
|
1287
|
+
var isHeldFlags = (value) => isRecord(value) && typeof value.hash === "string" && isRecord(value.flags);
|
|
1288
|
+
/**
|
|
1289
|
+
* The `scope` claim, read without verifying anything.
|
|
1290
|
+
*
|
|
1291
|
+
* Verification is the server's and this cannot do it — there is no signing key here, and a key this deployment does
|
|
1292
|
+
* not hold could not be checked anyway. Reading the claim is enough for what this is for: telling the operator, at
|
|
1293
|
+
* startup, that they pasted the wrong one of their two keys.
|
|
1294
|
+
*/
|
|
1295
|
+
var scopeOf = (token) => {
|
|
1296
|
+
const payload = token.split(".")[1];
|
|
1297
|
+
if (!payload) return;
|
|
1298
|
+
try {
|
|
1299
|
+
const claims = JSON.parse(Buffer.from(payload, "base64url").toString("utf8"));
|
|
1300
|
+
return typeof claims.scope === "string" ? claims.scope : void 0;
|
|
1301
|
+
} catch {
|
|
1302
|
+
return;
|
|
1303
|
+
}
|
|
1304
|
+
};
|
|
1305
|
+
/**
|
|
1306
|
+
* Refuse the PUBLIC key here, where the mistake is cheap, rather than as a 401 an hour later.
|
|
1307
|
+
*
|
|
1308
|
+
* The two keys are not interchangeable and the difference is the whole security model. A `render` key is embedded in
|
|
1309
|
+
* every published page, so anyone who views source has it; what keeps a copied one from working is that a browser is
|
|
1310
|
+
* made to state the origin it is presenting from, and that statement is checked. A server has no such statement to
|
|
1311
|
+
* make — which is exactly why a server must not be reading with the public key: if it could, a render key lifted
|
|
1312
|
+
* from someone else's site would be enough to serve a byte-identical clone of it from here.
|
|
1313
|
+
*
|
|
1314
|
+
* So self-hosting has a credential of its own. It is secret, issued once, bound to no domain, and revocable on its
|
|
1315
|
+
* own row without touching the published site's key.
|
|
1316
|
+
*/
|
|
1317
|
+
var assertHostKey = (webKey) => {
|
|
1318
|
+
const scope = scopeOf(webKey);
|
|
1319
|
+
if (scope === void 0 || scope === "space:host") return;
|
|
1320
|
+
if (scope === "space:render") throw new Error("createCloudAdapters was given the space’s PUBLIC render key. That key is embedded in published pages and is only honoured from the origins it declares, so a server cannot present it. Issue a host key instead (Credentials → “Self-hosting” in the builder, or POST /spaces/{id}/tokens/host) and keep it secret — it is not safe to commit or to ship in a page.");
|
|
1321
|
+
throw new Error(`createCloudAdapters needs a space host key; this one is scoped "${scope}".`);
|
|
1322
|
+
};
|
|
1323
|
+
var createCloudAdapters = (config) => {
|
|
1324
|
+
const { serverUrl = PLITZI_SERVER_URL, webKey, environment = "main", revision, cacheSeconds = 60, cache, spaceId = 1, deployment, fetchImpl = fetch } = config;
|
|
1325
|
+
assertHostKey(webKey);
|
|
1326
|
+
/** `main` is the document somebody is editing right now. Nothing about it is worth remembering for a minute. */
|
|
1327
|
+
const isLive = (env) => env === "main";
|
|
1328
|
+
/** A version somebody named: fetched once, kept for good, because a published revision cannot change. */
|
|
1329
|
+
const isPinned = (env, rev) => !isLive(env) && typeof rev === "number" && rev > 0;
|
|
1330
|
+
const post = async (query, variables, what) => {
|
|
1331
|
+
try {
|
|
1332
|
+
const response = await fetchImpl(serverUrl, {
|
|
1333
|
+
method: "POST",
|
|
1334
|
+
headers: {
|
|
1335
|
+
"Content-Type": "application/json",
|
|
1336
|
+
authorization: `Bearer ${webKey}`
|
|
1337
|
+
},
|
|
1338
|
+
body: JSON.stringify({
|
|
1339
|
+
query,
|
|
1340
|
+
variables
|
|
1341
|
+
})
|
|
1342
|
+
});
|
|
1343
|
+
if (!response.ok) {
|
|
1344
|
+
serverLog.error("CloudAdapters", `${what} answered ${response.status}`);
|
|
1345
|
+
return;
|
|
1346
|
+
}
|
|
1347
|
+
const payload = await response.json();
|
|
1348
|
+
if (payload.errors?.length) {
|
|
1349
|
+
serverLog.error("CloudAdapters", `${what}: ${payload.errors.map((error) => error.message).join("; ")}`);
|
|
1350
|
+
return;
|
|
1351
|
+
}
|
|
1352
|
+
return payload.data;
|
|
1353
|
+
} catch (error) {
|
|
1354
|
+
serverLog.error("CloudAdapters", `${what} could not be reached`, error);
|
|
1355
|
+
return;
|
|
1356
|
+
}
|
|
1357
|
+
};
|
|
1358
|
+
const fetchSpace = async (env, rev) => {
|
|
1359
|
+
const space = (await post(SPACE_QUERY, {
|
|
1360
|
+
environment: env,
|
|
1361
|
+
revision: rev ?? null
|
|
1362
|
+
}, `space ${env}@${rev ?? "latest"}`))?.Space;
|
|
1363
|
+
if (!space?.schema) return;
|
|
1364
|
+
return {
|
|
1365
|
+
schema: schemaFromWire(space.schema),
|
|
1366
|
+
style: space.style,
|
|
1367
|
+
plugins: space.plugins
|
|
1368
|
+
};
|
|
1369
|
+
};
|
|
1370
|
+
/** Which revision is current, and what the flags are at — one small question for both halves of a served space. */
|
|
1371
|
+
const probe = async (env) => {
|
|
1372
|
+
const answer = (await post(LATEST_REVISION_QUERY, { environment: env }, `latest revision of ${env}`))?.SpaceLatestRevision;
|
|
1373
|
+
return {
|
|
1374
|
+
revision: answer?.snapshot?.revision,
|
|
1375
|
+
flagsHash: answer?.flagsHash ?? void 0
|
|
1376
|
+
};
|
|
1377
|
+
};
|
|
1378
|
+
const cacheKey = (env, rev) => `plitzi:space:${env}:${rev}`;
|
|
1379
|
+
const flagsCacheKey = (env) => `plitzi:flags:${env}`;
|
|
1380
|
+
/** Each environment's flags as last fetched, and when the probe last confirmed them. */
|
|
1381
|
+
const heldFlags = /* @__PURE__ */ new Map();
|
|
1382
|
+
/** The flags this process last held, or — on a cold start — the shared cache's, so a restart with Plitzi down keeps
|
|
1383
|
+
* serving the flags it knew rather than the ones frozen into a cached revision. */
|
|
1384
|
+
const restoreFlags = async (env) => {
|
|
1385
|
+
if (heldFlags.has(env)) return;
|
|
1386
|
+
try {
|
|
1387
|
+
const stored = await cache?.get(flagsCacheKey(env));
|
|
1388
|
+
const held = stored ? JSON.parse(stored) : void 0;
|
|
1389
|
+
if (isHeldFlags(held)) heldFlags.set(env, {
|
|
1390
|
+
...held,
|
|
1391
|
+
checkedAt: 0
|
|
1392
|
+
});
|
|
1393
|
+
} catch {}
|
|
1394
|
+
};
|
|
1395
|
+
/** Brings the flags up to the hash the probe answered, fetching them only when it moved. A failed probe or fetch keeps
|
|
1396
|
+
* the flags already held. */
|
|
1397
|
+
const syncFlags = async (env, hash) => {
|
|
1398
|
+
if (hash === void 0) return;
|
|
1399
|
+
const current = heldFlags.get(env);
|
|
1400
|
+
if (current?.hash === hash) {
|
|
1401
|
+
current.checkedAt = Date.now();
|
|
1402
|
+
return;
|
|
1403
|
+
}
|
|
1404
|
+
const fetched = (await post(FLAGS_QUERY, { environment: env }, `flags of ${env}`))?.SpaceFlags;
|
|
1405
|
+
if (!fetched) return;
|
|
1406
|
+
heldFlags.set(env, {
|
|
1407
|
+
...fetched,
|
|
1408
|
+
checkedAt: Date.now()
|
|
1409
|
+
});
|
|
1410
|
+
await cache?.set(flagsCacheKey(env), JSON.stringify(fetched)).catch(() => void 0);
|
|
1411
|
+
};
|
|
1412
|
+
/** A served space with the flags held for its environment — the same object for the same pair, so the page server
|
|
1413
|
+
* serialises it once rather than per request. */
|
|
1414
|
+
const combined = /* @__PURE__ */ new WeakMap();
|
|
1415
|
+
const withFlags = (env, data) => {
|
|
1416
|
+
const flags = heldFlags.get(env);
|
|
1417
|
+
if (!flags) return data;
|
|
1418
|
+
const known = combined.get(data);
|
|
1419
|
+
if (known?.hash === flags.hash) return known.data;
|
|
1420
|
+
const joined = {
|
|
1421
|
+
...data,
|
|
1422
|
+
schema: {
|
|
1423
|
+
...data.schema,
|
|
1424
|
+
flags: flags.flags
|
|
1425
|
+
}
|
|
1426
|
+
};
|
|
1427
|
+
combined.set(data, {
|
|
1428
|
+
hash: flags.hash,
|
|
1429
|
+
data: joined
|
|
1430
|
+
});
|
|
1431
|
+
return joined;
|
|
1432
|
+
};
|
|
1433
|
+
const held = /* @__PURE__ */ new Map();
|
|
1434
|
+
/** One request per key at a time: a burst of renders on a cold cache joins the first, it does not multiply it. */
|
|
1435
|
+
const inFlight = /* @__PURE__ */ new Map();
|
|
1436
|
+
const once = (key, run) => {
|
|
1437
|
+
const pending = inFlight.get(key);
|
|
1438
|
+
if (pending) return pending;
|
|
1439
|
+
const request = run().finally(() => inFlight.delete(key));
|
|
1440
|
+
inFlight.set(key, request);
|
|
1441
|
+
return request;
|
|
1442
|
+
};
|
|
1443
|
+
/** Reads a published revision through the shared cache, then the network, and writes back what it learned. */
|
|
1444
|
+
const loadRevision = (env, rev) => {
|
|
1445
|
+
const key = cacheKey(env, rev);
|
|
1446
|
+
return once(key, async () => {
|
|
1447
|
+
try {
|
|
1448
|
+
const stored = await cache?.get(key);
|
|
1449
|
+
if (stored) {
|
|
1450
|
+
const data = JSON.parse(stored);
|
|
1451
|
+
held.set(env, {
|
|
1452
|
+
revision: rev,
|
|
1453
|
+
data,
|
|
1454
|
+
checkedAt: Date.now()
|
|
1455
|
+
});
|
|
1456
|
+
return data;
|
|
1457
|
+
}
|
|
1458
|
+
} catch {}
|
|
1459
|
+
const fetched = await fetchSpace(env, rev);
|
|
1460
|
+
if (!fetched) return;
|
|
1461
|
+
held.set(env, {
|
|
1462
|
+
revision: rev,
|
|
1463
|
+
data: fetched,
|
|
1464
|
+
checkedAt: Date.now()
|
|
1465
|
+
});
|
|
1466
|
+
await cache?.set(key, JSON.stringify(fetched)).catch(() => void 0);
|
|
1467
|
+
return fetched;
|
|
1468
|
+
});
|
|
1469
|
+
};
|
|
1470
|
+
/**
|
|
1471
|
+
* Latest mode: find out which revision is current, and fetch the space only if that moved.
|
|
1472
|
+
*
|
|
1473
|
+
* The probe is the thing on the timer, not the space. A deployment that publishes once a week asks Plitzi for a
|
|
1474
|
+
* revision number every minute and for a space once — and a publish is live within one window rather than
|
|
1475
|
+
* whenever a blanket TTL happened to fall.
|
|
1476
|
+
*
|
|
1477
|
+
* A probe that fails leaves `checkedAt` alone so the next request tries again, and leaves the held copy serving.
|
|
1478
|
+
*/
|
|
1479
|
+
const refreshLatest = async (env) => {
|
|
1480
|
+
await restoreFlags(env);
|
|
1481
|
+
const { revision: current, flagsHash } = await probe(env);
|
|
1482
|
+
await syncFlags(env, flagsHash);
|
|
1483
|
+
const previous = held.get(env);
|
|
1484
|
+
if (current === void 0) return previous?.data;
|
|
1485
|
+
if (previous && previous.revision === current) {
|
|
1486
|
+
previous.checkedAt = Date.now();
|
|
1487
|
+
return previous.data;
|
|
1488
|
+
}
|
|
1489
|
+
return await loadRevision(env, current) ?? previous?.data;
|
|
1490
|
+
};
|
|
1491
|
+
/**
|
|
1492
|
+
* A pinned revision's flags: waited for once — the first render must not go out with the flags frozen into the copy
|
|
1493
|
+
* it fetched — and then checked behind the answer, on the window.
|
|
1494
|
+
*/
|
|
1495
|
+
const refreshPinnedFlags = async (env) => {
|
|
1496
|
+
await restoreFlags(env);
|
|
1497
|
+
const flags = heldFlags.get(env);
|
|
1498
|
+
if (!flags) {
|
|
1499
|
+
await syncFlags(env, (await probe(env)).flagsHash);
|
|
1500
|
+
return;
|
|
1501
|
+
}
|
|
1502
|
+
if (Date.now() - flags.checkedAt >= cacheSeconds * 1e3) {
|
|
1503
|
+
flags.checkedAt = Date.now();
|
|
1504
|
+
probe(env).then(({ flagsHash }) => syncFlags(env, flagsHash)).catch(() => void 0);
|
|
1505
|
+
}
|
|
1506
|
+
};
|
|
1507
|
+
/**
|
|
1508
|
+
* The space, and how hard this deployment leans on Plitzi to get it.
|
|
1509
|
+
*
|
|
1510
|
+
* - **`main`**: read live, every time. It is being edited; a cached answer is a wrong one.
|
|
1511
|
+
* - **A pinned revision**: from cache forever after the first read. It cannot change — its flags can, so they are
|
|
1512
|
+
* probed on the same window as the latest mode's revision, and fetched only when they moved.
|
|
1513
|
+
* - **Latest**: the held copy is served immediately and a revision probe runs behind it once the window is up.
|
|
1514
|
+
* After the first render no page ever waits on Plitzi, and a failed probe or fetch changes nothing — the last
|
|
1515
|
+
* good copy keeps serving, because a self-hosted site going blank over somebody else's bad minute is not a
|
|
1516
|
+
* trade worth making.
|
|
1517
|
+
*/
|
|
1518
|
+
const getOfflineData = async (_spaceId, env, rev) => {
|
|
1519
|
+
if (isLive(env)) return once(`live:${env}`, () => fetchSpace(env));
|
|
1520
|
+
const pinned = rev ?? revision;
|
|
1521
|
+
if (pinned !== void 0 && isPinned(env, pinned)) {
|
|
1522
|
+
await refreshPinnedFlags(env);
|
|
1523
|
+
const already = held.get(env);
|
|
1524
|
+
const data = already?.revision === pinned ? already.data : await loadRevision(env, pinned);
|
|
1525
|
+
return data && withFlags(env, data);
|
|
1526
|
+
}
|
|
1527
|
+
const current = held.get(env);
|
|
1528
|
+
if (!current) {
|
|
1529
|
+
const data = await refreshLatest(env);
|
|
1530
|
+
return data && withFlags(env, data);
|
|
1531
|
+
}
|
|
1532
|
+
if (Date.now() - current.checkedAt >= cacheSeconds * 1e3) {
|
|
1533
|
+
current.checkedAt = Date.now();
|
|
1534
|
+
refreshLatest(env).catch(() => void 0);
|
|
1535
|
+
}
|
|
1536
|
+
return withFlags(env, current.data);
|
|
1537
|
+
};
|
|
1538
|
+
/**
|
|
1539
|
+
* Every request is this one space.
|
|
1540
|
+
*
|
|
1541
|
+
* There is no host-to-space mapping to make: the key names the space, so a deployment that serves two of them
|
|
1542
|
+
* builds two servers or supplies its own resolver — which is more honest than a lookup table that silently
|
|
1543
|
+
* serves the wrong space when a domain is added and this is not.
|
|
1544
|
+
*
|
|
1545
|
+
* The revision it reports is the one actually being served, with what its flags are at, which in latest mode is whatever the last probe
|
|
1546
|
+
* found: a deployment reading `at: { environment, revision }` must be told the version its page was built from,
|
|
1547
|
+
* not the zero that means "whatever is live".
|
|
1548
|
+
*/
|
|
1549
|
+
const getSpaceDeployment = async () => {
|
|
1550
|
+
if (isLive(environment)) return {
|
|
1551
|
+
...deployment,
|
|
1552
|
+
spaceId,
|
|
1553
|
+
environment,
|
|
1554
|
+
revision: 0
|
|
1555
|
+
};
|
|
1556
|
+
const flagsVersion = () => {
|
|
1557
|
+
const flags = heldFlags.get(environment);
|
|
1558
|
+
return flags ? { flagsVersion: flags.hash } : {};
|
|
1559
|
+
};
|
|
1560
|
+
if (isPinned(environment, revision)) {
|
|
1561
|
+
await refreshPinnedFlags(environment);
|
|
1562
|
+
return {
|
|
1563
|
+
...deployment,
|
|
1564
|
+
spaceId,
|
|
1565
|
+
environment,
|
|
1566
|
+
revision,
|
|
1567
|
+
...flagsVersion()
|
|
1568
|
+
};
|
|
1569
|
+
}
|
|
1570
|
+
if (!held.has(environment)) await refreshLatest(environment);
|
|
1571
|
+
return {
|
|
1572
|
+
...deployment,
|
|
1573
|
+
spaceId,
|
|
1574
|
+
environment,
|
|
1575
|
+
revision: held.get(environment)?.revision ?? 0,
|
|
1576
|
+
...flagsVersion()
|
|
1577
|
+
};
|
|
1578
|
+
};
|
|
1579
|
+
return {
|
|
1580
|
+
getOfflineData,
|
|
1581
|
+
getSpaceDeployment
|
|
1582
|
+
};
|
|
1583
|
+
};
|
|
1584
|
+
// src/adapters/jsonAdapters.ts
|
|
1585
|
+
var isDeploymentObject = (v) => typeof v === "object" && ("spaceId" in v || "environment" in v || "error" in v);
|
|
1586
|
+
var createJsonReader = () => {
|
|
1587
|
+
const held = /* @__PURE__ */ new Map();
|
|
1588
|
+
return {
|
|
1589
|
+
read: (filePath) => {
|
|
1590
|
+
const { mtimeMs, size } = statSync(filePath);
|
|
1591
|
+
const hit = held.get(filePath);
|
|
1592
|
+
if (hit?.mtimeMs === mtimeMs && hit.size === size) return hit.value;
|
|
1593
|
+
const value = JSON.parse(readFileSync(filePath, "utf-8"));
|
|
1594
|
+
held.set(filePath, {
|
|
1595
|
+
mtimeMs,
|
|
1596
|
+
size,
|
|
1597
|
+
value
|
|
1598
|
+
});
|
|
1599
|
+
return value;
|
|
1600
|
+
},
|
|
1601
|
+
forget: (filePath) => {
|
|
1602
|
+
held.delete(filePath);
|
|
1603
|
+
}
|
|
1604
|
+
};
|
|
1605
|
+
};
|
|
1606
|
+
var createJsonAdapters = (config) => {
|
|
1607
|
+
const json = createJsonReader();
|
|
1608
|
+
const sourceFor = (spaceId, environment, revision) => typeof config.offlineData === "function" ? config.offlineData(spaceId, environment, revision) : config.offlineData;
|
|
1609
|
+
const getOfflineData = (spaceId, environment, revision) => {
|
|
1610
|
+
try {
|
|
1611
|
+
const source = sourceFor(spaceId, environment, revision);
|
|
1612
|
+
return Promise.resolve(typeof source === "string" ? json.read(source) : source);
|
|
1613
|
+
} catch (err) {
|
|
1614
|
+
serverLog.error("JsonAdapters", "Failed to read offlineData", err);
|
|
1615
|
+
return Promise.resolve(void 0);
|
|
1616
|
+
}
|
|
1617
|
+
};
|
|
1618
|
+
const getSchema = async (spaceId, environment) => (await getOfflineData(spaceId, environment))?.schema;
|
|
1619
|
+
const getStyle = async (spaceId, environment) => (await getOfflineData(spaceId, environment))?.style;
|
|
1620
|
+
const writeBack = (spaceId, environment, change) => {
|
|
1621
|
+
const filePath = sourceFor(spaceId, environment);
|
|
1622
|
+
if (typeof filePath !== "string") return Promise.reject(/* @__PURE__ */ new Error(`Space ${String(spaceId)} (${environment}) is held in memory, not in a file: there is nowhere to save it.`));
|
|
1623
|
+
const current = json.read(filePath);
|
|
1624
|
+
writeFileSync(filePath, JSON.stringify({
|
|
1625
|
+
...current,
|
|
1626
|
+
...change
|
|
1627
|
+
}, null, 2));
|
|
1628
|
+
json.forget(filePath);
|
|
1629
|
+
return Promise.resolve();
|
|
1630
|
+
};
|
|
1631
|
+
const saveSchema = (spaceId, environment, schema) => writeBack(spaceId, environment, { schema });
|
|
1632
|
+
const saveStyle = (spaceId, environment, style) => writeBack(spaceId, environment, { style });
|
|
1633
|
+
const getSpaceDeployment = (req) => {
|
|
1634
|
+
const { deployment } = config;
|
|
1635
|
+
if (!deployment) return Promise.resolve({
|
|
1636
|
+
spaceId: 1,
|
|
1637
|
+
environment: "main",
|
|
1638
|
+
revision: 0
|
|
1639
|
+
});
|
|
1640
|
+
if (typeof deployment === "string") try {
|
|
1641
|
+
return Promise.resolve(json.read(deployment));
|
|
1642
|
+
} catch (err) {
|
|
1643
|
+
serverLog.error("JsonAdapters", "Failed to read deployment file", err);
|
|
1644
|
+
return Promise.resolve({ error: {
|
|
1645
|
+
code: 500,
|
|
1646
|
+
message: "Deployment config unreadable"
|
|
1647
|
+
} });
|
|
1648
|
+
}
|
|
1649
|
+
if (isDeploymentObject(deployment)) return Promise.resolve(deployment);
|
|
1650
|
+
const byHostname = deployment;
|
|
1651
|
+
return Promise.resolve(byHostname[req.hostname] ?? byHostname["*"] ?? {
|
|
1652
|
+
spaceId: 1,
|
|
1653
|
+
environment: "main",
|
|
1654
|
+
revision: 0
|
|
1655
|
+
});
|
|
1656
|
+
};
|
|
1657
|
+
return {
|
|
1658
|
+
getOfflineData,
|
|
1659
|
+
getSpaceDeployment,
|
|
1660
|
+
getSchema,
|
|
1661
|
+
getStyle,
|
|
1662
|
+
...typeof config.offlineData !== "object" ? {
|
|
1663
|
+
saveSchema,
|
|
1664
|
+
saveStyle
|
|
1665
|
+
} : {}
|
|
1666
|
+
};
|
|
1667
|
+
};
|
|
1668
|
+
// src/adapters/authAdapters.ts
|
|
1669
|
+
var createAuthAdapters = (config) => {
|
|
1670
|
+
const { user, authenticate, endSession } = config;
|
|
1671
|
+
const getUser = user ? (req) => Promise.resolve(typeof user === "function" ? user(req) : user) : void 0;
|
|
1672
|
+
return {
|
|
1673
|
+
...getUser ? { getUser } : {},
|
|
1674
|
+
...authenticate ? { authenticate } : {},
|
|
1675
|
+
...endSession ? { endSession } : {}
|
|
1676
|
+
};
|
|
1677
|
+
};
|
|
1678
|
+
// src/adapters/space/types.ts
|
|
1679
|
+
var isRefusal = (value) => "refuse" in value;
|
|
1680
|
+
/** A resolver's refusal, as the one-liner it deserves to be at a call site. */
|
|
1681
|
+
var refuse = (code, message) => ({ refuse: {
|
|
1682
|
+
code,
|
|
1683
|
+
message
|
|
1684
|
+
} });
|
|
1685
|
+
/**
|
|
1686
|
+
* A cache in this process's memory, for a deployment that runs one.
|
|
1687
|
+
*
|
|
1688
|
+
* Say that out loud before using it: each process keeps its own, so invalidating on one does not invalidate on the
|
|
1689
|
+
* others, and a deployment behind more than one replica will serve a stale resolution from the replicas that were
|
|
1690
|
+
* not told. That is fine for a single-process server and wrong for a cluster, which wants Redis or nothing.
|
|
1691
|
+
*/
|
|
1692
|
+
var createMemoryCache = () => {
|
|
1693
|
+
const entries = /* @__PURE__ */ new Map();
|
|
1694
|
+
return {
|
|
1695
|
+
get: (key) => {
|
|
1696
|
+
const entry = entries.get(key);
|
|
1697
|
+
if (!entry) return Promise.resolve(void 0);
|
|
1698
|
+
if (Date.now() > entry.expiresAt) {
|
|
1699
|
+
entries.delete(key);
|
|
1700
|
+
return Promise.resolve(void 0);
|
|
1701
|
+
}
|
|
1702
|
+
return Promise.resolve(entry.value);
|
|
1703
|
+
},
|
|
1704
|
+
set: (key, value, ttlSeconds) => {
|
|
1705
|
+
entries.set(key, {
|
|
1706
|
+
value,
|
|
1707
|
+
expiresAt: Date.now() + ttlSeconds * 1e3
|
|
1708
|
+
});
|
|
1709
|
+
return Promise.resolve();
|
|
1710
|
+
},
|
|
1711
|
+
delete: (key) => {
|
|
1712
|
+
entries.delete(key);
|
|
1713
|
+
return Promise.resolve();
|
|
1714
|
+
}
|
|
1715
|
+
};
|
|
1716
|
+
};
|
|
1717
|
+
// src/adapters/space/resolvers.ts
|
|
1718
|
+
/**
|
|
1719
|
+
* Did this request even try to present a credential?
|
|
1720
|
+
*
|
|
1721
|
+
* Not "is the credential good" — that is `resolveGrant`'s answer, and asking it of every anonymous visitor who
|
|
1722
|
+
* lands on a first-party host would turn them all into 403s. This is the gate before it, and it is also what marks
|
|
1723
|
+
* a request as un-cacheable: the shared resolution cache is keyed by host, and a request carrying a credential can
|
|
1724
|
+
* resolve to a different space than the same host without one.
|
|
1725
|
+
*/
|
|
1726
|
+
var presentsCredential = (req) => Boolean(req.query["access-token"]) || Boolean(req.headers.authorization);
|
|
1727
|
+
/**
|
|
1728
|
+
* The ordinary case: a custom domain someone pointed at this server, resolved through a row that says it was
|
|
1729
|
+
* verified. Returns nothing when the domain is unknown, so a later resolver still gets a turn.
|
|
1730
|
+
*/
|
|
1731
|
+
var verifiedDomain = (find) => {
|
|
1732
|
+
return async (req) => {
|
|
1733
|
+
const row = await find(req.hostname);
|
|
1734
|
+
if (!row) return;
|
|
1735
|
+
if (row.verified === false) return refuse(404, "Domain not verified");
|
|
1736
|
+
const { spaceId, environment, credential, security } = row;
|
|
1737
|
+
return {
|
|
1738
|
+
spaceId,
|
|
1739
|
+
...environment ? { environment } : {},
|
|
1740
|
+
revision: row.revision ?? 0,
|
|
1741
|
+
...credential ? { credential } : {},
|
|
1742
|
+
...security ? { security } : {}
|
|
1743
|
+
};
|
|
1744
|
+
};
|
|
1745
|
+
};
|
|
1746
|
+
/**
|
|
1747
|
+
* Every space reachable at `<slug>.example.com` without anybody configuring a domain for it.
|
|
1748
|
+
*
|
|
1749
|
+
* The point is that it needs no per-space row: the sub-domain is the identifier, so a space is publishable the
|
|
1750
|
+
* moment it exists. It always resolves the live snapshot — a free preview domain that served a pinned revision
|
|
1751
|
+
* would be a second thing to deploy to.
|
|
1752
|
+
*/
|
|
1753
|
+
var wildcardSubdomain = ({ suffix, find }) => {
|
|
1754
|
+
const dotted = suffix.startsWith(".") ? suffix : `.${suffix}`;
|
|
1755
|
+
return async (req) => {
|
|
1756
|
+
if (!req.hostname.endsWith(dotted)) return;
|
|
1757
|
+
const slug = req.hostname.slice(0, -dotted.length);
|
|
1758
|
+
if (!slug || slug.includes(".")) return;
|
|
1759
|
+
const space = await find(slug);
|
|
1760
|
+
return space ? {
|
|
1761
|
+
...space,
|
|
1762
|
+
revision: 0
|
|
1763
|
+
} : void 0;
|
|
1764
|
+
};
|
|
1765
|
+
};
|
|
1766
|
+
/**
|
|
1767
|
+
* An author looking at their own space through a builder, rather than a visitor being served.
|
|
1768
|
+
*
|
|
1769
|
+
* Put this FIRST. It engages only when a credential is presented on a host this deployment owns, and once it has,
|
|
1770
|
+
* a bad credential is a refusal rather than a fall-through — a request that tried to act for a space and failed
|
|
1771
|
+
* must not then be served as an anonymous visitor of whatever else that host resolves to.
|
|
1772
|
+
*
|
|
1773
|
+
* `skipOrigin` is deliberate: a preview is loaded as a document, and a top-level navigation carries no `Origin`.
|
|
1774
|
+
* It does not skip the domain binding, which is the part that matters.
|
|
1775
|
+
*
|
|
1776
|
+
* The space's PUBLIC key (`render`) is in every published page: presented alone it names the space — a tool's page (a
|
|
1777
|
+
* thumbnail, a journey) opens with it, and a draft it carries is what makes it a preview — but it is a visit, metered as
|
|
1778
|
+
* one. An author's render is the one `isAuthor` vouches for: held as `authoring`, a copied key would serve anyone the
|
|
1779
|
+
* space unmetered from a host of this deployment.
|
|
1780
|
+
*/
|
|
1781
|
+
var authoringPreview = ({ hosts, resolveGrant, find, presented = presentsCredential, isAuthor }) => {
|
|
1782
|
+
return async (req) => {
|
|
1783
|
+
if (!hosts.includes(req.hostname) || !presented(req)) return;
|
|
1784
|
+
const result = await resolveGrant(req, { skipOrigin: true });
|
|
1785
|
+
if (!result.ok) return refuse(403, "Access Not Authorized");
|
|
1786
|
+
const space = await find(result.grant.spaceId);
|
|
1787
|
+
if (!space) return refuse(404, "Space not found");
|
|
1788
|
+
const authoring = result.grant.scope !== "render" || (await isAuthor?.(req, result.grant) ?? false);
|
|
1789
|
+
return {
|
|
1790
|
+
...space,
|
|
1791
|
+
revision: 0,
|
|
1792
|
+
...authoring ? { authoring: true } : {}
|
|
1793
|
+
};
|
|
1794
|
+
};
|
|
1795
|
+
};
|
|
1796
|
+
var ENVIRONMENTS = [
|
|
1797
|
+
"main",
|
|
1798
|
+
"production",
|
|
1799
|
+
"staging",
|
|
1800
|
+
"development"
|
|
1801
|
+
];
|
|
1802
|
+
var isEnvironment = (value) => value !== void 0 && ENVIRONMENTS.includes(value);
|
|
1803
|
+
/**
|
|
1804
|
+
* A page that renders the space itself — a site published as files, an embed, the desktop app — asking for it with the
|
|
1805
|
+
* space's public `render` credential, from wherever it is served.
|
|
1806
|
+
*
|
|
1807
|
+
* Put this BEFORE `authoringPreview`: an author's credential is not this one's, and goes on to it. Only the
|
|
1808
|
+
* credential in `Authorization`, which a page's `fetch` sends: one in the address (`?access-token`) is a page opened
|
|
1809
|
+
* by a tool — a screenshot, a journey — and stays what it was. The grant is checked with the page's `Origin` and the
|
|
1810
|
+
* host it was presented on, as every browser credential is; it names the space, and the request the environment and
|
|
1811
|
+
* revision — the live one when it names none, which is what a published site asks for.
|
|
1812
|
+
*/
|
|
1813
|
+
var renderGrant = ({ resolveGrant, find }) => {
|
|
1814
|
+
return async (req) => {
|
|
1815
|
+
if (!req.headers.authorization) return;
|
|
1816
|
+
const result = await resolveGrant(req, { host: req.hostname });
|
|
1817
|
+
if (!result.ok || result.grant.scope !== "render") return;
|
|
1818
|
+
const space = await find(result.grant.spaceId);
|
|
1819
|
+
if (!space) return refuse(404, "Space not found");
|
|
1820
|
+
const asked = req.query.environment;
|
|
1821
|
+
if (asked && !isEnvironment(asked)) return refuse(400, `No environment "${asked}": ask for one of ${ENVIRONMENTS.join(", ")}, or none for the live one`);
|
|
1822
|
+
const revision = Number(req.query.revision);
|
|
1823
|
+
return {
|
|
1824
|
+
spaceId: space.spaceId,
|
|
1825
|
+
environment: isEnvironment(asked) ? asked : space.environment ?? "main",
|
|
1826
|
+
revision: Number.isInteger(revision) && revision > 0 ? revision : 0,
|
|
1827
|
+
grantOrigins: result.grant.origins
|
|
1828
|
+
};
|
|
1829
|
+
};
|
|
1830
|
+
};
|
|
1831
|
+
/** A space this server always serves, whatever the host — a single-space deployment, or the last word in a chain. */
|
|
1832
|
+
var fixedSpace = (resolution) => {
|
|
1833
|
+
return () => Promise.resolve(resolution);
|
|
1834
|
+
};
|
|
1835
|
+
// src/adapters/space/index.ts
|
|
1836
|
+
var RESOLUTION_PREFIX = "space:resolution:";
|
|
1837
|
+
var DOMAINS_PREFIX = "space:domains:";
|
|
1838
|
+
/**
|
|
1839
|
+
* `getSpaceDeployment`, assembled.
|
|
1840
|
+
*
|
|
1841
|
+
* Answering "which space is this request for" is the same shape everywhere and the same *rules* everywhere — try
|
|
1842
|
+
* the ways a host can name a space, in order; never serve a credentialed request from a shared cache; derive the
|
|
1843
|
+
* framing policy from what the space declared; say 404 rather than leaking whether a space exists. What differs
|
|
1844
|
+
* between deployments is only where the rows are, which is what a resolver is.
|
|
1845
|
+
*
|
|
1846
|
+
* ```ts
|
|
1847
|
+
* const spaces = createSpaceAdapters({
|
|
1848
|
+
* resolvers: [
|
|
1849
|
+
* authoringPreview({ hosts, resolveGrant: auth.identity.resolveGrant, find: findSpace }),
|
|
1850
|
+
* wildcardSubdomain({ suffix: 'example.app', find: findSpaceBySlug }),
|
|
1851
|
+
* verifiedDomain(findDeploymentByDomain)
|
|
1852
|
+
* ],
|
|
1853
|
+
* cache: redisCache,
|
|
1854
|
+
* frameAncestors: { find: findSpaceDomains, floor: hosts, cache: true }
|
|
1855
|
+
* });
|
|
1856
|
+
*
|
|
1857
|
+
* createServer({ adapters: { ...spaces.adapters, getOfflineData } });
|
|
1858
|
+
* ```
|
|
1859
|
+
*/
|
|
1860
|
+
var createSpaceAdapters = (config) => {
|
|
1861
|
+
const { resolvers, cache, ttlSeconds = 300, cacheKey = (req) => presentsCredential(req) ? void 0 : req.hostname, frameAncestors: frameAncestors$1, decorate, notFound = {
|
|
1862
|
+
code: 404,
|
|
1863
|
+
message: "Space not found"
|
|
1864
|
+
}, onError } = config;
|
|
1865
|
+
const readCache = async (key) => {
|
|
1866
|
+
if (!cache) return;
|
|
1867
|
+
try {
|
|
1868
|
+
const raw = await cache.get(key);
|
|
1869
|
+
return raw === void 0 ? void 0 : JSON.parse(raw);
|
|
1870
|
+
} catch (error) {
|
|
1871
|
+
onError?.(error);
|
|
1872
|
+
return;
|
|
1873
|
+
}
|
|
1874
|
+
};
|
|
1875
|
+
const writeCache = async (key, value) => {
|
|
1876
|
+
if (!cache) return;
|
|
1877
|
+
try {
|
|
1878
|
+
await cache.set(key, JSON.stringify(value), ttlSeconds);
|
|
1879
|
+
} catch (error) {
|
|
1880
|
+
onError?.(error);
|
|
1881
|
+
}
|
|
1882
|
+
};
|
|
1883
|
+
const domainsOf = async (spaceId) => {
|
|
1884
|
+
if (!frameAncestors$1) return [];
|
|
1885
|
+
const key = `${DOMAINS_PREFIX}${spaceId}`;
|
|
1886
|
+
if (frameAncestors$1.cache) {
|
|
1887
|
+
const cached = await readCache(key);
|
|
1888
|
+
if (cached) return cached;
|
|
1889
|
+
}
|
|
1890
|
+
const domains = await frameAncestors$1.find(spaceId);
|
|
1891
|
+
if (frameAncestors$1.cache) await writeCache(key, domains);
|
|
1892
|
+
return domains;
|
|
1893
|
+
};
|
|
1894
|
+
/** Everything that is true of a resolution regardless of which resolver produced it. */
|
|
1895
|
+
const complete = async (resolution, req) => {
|
|
1896
|
+
const decorated = decorate ? {
|
|
1897
|
+
...resolution,
|
|
1898
|
+
...await decorate(resolution, req)
|
|
1899
|
+
} : resolution;
|
|
1900
|
+
return {
|
|
1901
|
+
environment: "main",
|
|
1902
|
+
revision: 0,
|
|
1903
|
+
...decorated,
|
|
1904
|
+
...frameAncestors$1 ? { frameAncestors: frameAncestors(await domainsOf(decorated.spaceId), frameAncestors$1.floor ?? []) } : {}
|
|
1905
|
+
};
|
|
1906
|
+
};
|
|
1907
|
+
const runResolvers = async (req) => {
|
|
1908
|
+
for (const resolve of resolvers) {
|
|
1909
|
+
const answer = await resolve(req);
|
|
1910
|
+
if (answer) return answer;
|
|
1911
|
+
}
|
|
1912
|
+
};
|
|
1913
|
+
const getSpaceDeployment = async (req) => {
|
|
1914
|
+
const key = cacheKey(req);
|
|
1915
|
+
try {
|
|
1916
|
+
if (key !== void 0) {
|
|
1917
|
+
const cached = await readCache(`${RESOLUTION_PREFIX}${key}`);
|
|
1918
|
+
if (cached) return await complete(cached, req);
|
|
1919
|
+
}
|
|
1920
|
+
const answer = await runResolvers(req);
|
|
1921
|
+
if (!answer) return { error: notFound };
|
|
1922
|
+
if (isRefusal(answer)) return { error: answer.refuse };
|
|
1923
|
+
if (key !== void 0 && !answer.authoring) await writeCache(`${RESOLUTION_PREFIX}${key}`, answer);
|
|
1924
|
+
return await complete(answer, req);
|
|
1925
|
+
} catch (error) {
|
|
1926
|
+
onError?.(error, req);
|
|
1927
|
+
return { error: {
|
|
1928
|
+
code: 500,
|
|
1929
|
+
message: "Space could not be resolved"
|
|
1930
|
+
} };
|
|
1931
|
+
}
|
|
1932
|
+
};
|
|
1933
|
+
return {
|
|
1934
|
+
/** Spread into `createServer({ adapters })` beside whatever answers `getOfflineData`. */
|
|
1935
|
+
adapters: { getSpaceDeployment },
|
|
1936
|
+
getSpaceDeployment,
|
|
1937
|
+
/**
|
|
1938
|
+
* Drop what a change made untrue. Both matter the moment an owner edits something through an API: without the
|
|
1939
|
+
* first a domain keeps resolving to the space it used to, and without the second a space stays framable by a
|
|
1940
|
+
* site whose permission was just withdrawn — in both cases until the TTL, which is not a security boundary.
|
|
1941
|
+
*/
|
|
1942
|
+
invalidate: {
|
|
1943
|
+
resolution: async (key) => {
|
|
1944
|
+
await cache?.delete(`${RESOLUTION_PREFIX}${key}`);
|
|
1945
|
+
},
|
|
1946
|
+
domains: async (spaceId) => {
|
|
1947
|
+
await cache?.delete(`${DOMAINS_PREFIX}${spaceId}`);
|
|
1948
|
+
}
|
|
1949
|
+
}
|
|
1950
|
+
};
|
|
1951
|
+
};
|
|
1952
|
+
// src/modules/ssr/redisPageStore.ts
|
|
1953
|
+
/**
|
|
1954
|
+
* The pages, kept in Lua so a page and its accounting never come apart — a segmented LRU, as each process's own
|
|
1955
|
+
* (`TtlCache`): a page starts on probation and is protected once it is used again (read by a replica, or stored again by
|
|
1956
|
+
* one); probation gives way first, and protected pages past 80% of the budget go back to it.
|
|
1957
|
+
* - `page:<key>`, the page, with its TTL; `where`, each page's `<spaceId>\n<environment>\n<host>`; `sizes`, its bytes;
|
|
1958
|
+
* - `space:<spaceId>`, a space's pages, which an invalidation reads, and `spaces`, the spaces that have any;
|
|
1959
|
+
* - `probation` and `protected`, the pages by when they were last used, and `bytes:<lane>`, what each holds.
|
|
1960
|
+
* KEYS[1] is the prefix: every key a script touches is built from it, and naming it routes the script to the node of a
|
|
1961
|
+
* Redis Cluster that holds them (its hash tag).
|
|
1962
|
+
*/
|
|
1963
|
+
var LANES = `
|
|
1964
|
+
local LANES = { 'probation', 'protected' }
|
|
1965
|
+
|
|
1966
|
+
local function evict(prefix, key)
|
|
1967
|
+
local where = redis.call('HGET', prefix .. 'where', key)
|
|
1968
|
+
if where then
|
|
1969
|
+
local space = string.match(where, '^([^\\n]*)\\n')
|
|
1970
|
+
redis.call('SREM', prefix .. 'space:' .. space, key)
|
|
1971
|
+
if redis.call('SCARD', prefix .. 'space:' .. space) == 0 then
|
|
1972
|
+
redis.call('SREM', prefix .. 'spaces', space)
|
|
1973
|
+
end
|
|
1974
|
+
end
|
|
1975
|
+
local size = tonumber(redis.call('HGET', prefix .. 'sizes', key) or '0')
|
|
1976
|
+
for _, lane in ipairs(LANES) do
|
|
1977
|
+
if redis.call('ZREM', prefix .. lane, key) == 1 then
|
|
1978
|
+
redis.call('DECRBY', prefix .. 'bytes:' .. lane, size)
|
|
1979
|
+
end
|
|
1980
|
+
end
|
|
1981
|
+
redis.call('HDEL', prefix .. 'where', key)
|
|
1982
|
+
redis.call('HDEL', prefix .. 'sizes', key)
|
|
1983
|
+
return redis.call('DEL', prefix .. 'page:' .. key)
|
|
1984
|
+
end
|
|
1985
|
+
|
|
1986
|
+
local function place(prefix, key, lane, now)
|
|
1987
|
+
local size = tonumber(redis.call('HGET', prefix .. 'sizes', key) or '0')
|
|
1988
|
+
for _, other in ipairs(LANES) do
|
|
1989
|
+
if other ~= lane and redis.call('ZREM', prefix .. other, key) == 1 then
|
|
1990
|
+
redis.call('DECRBY', prefix .. 'bytes:' .. other, size)
|
|
1991
|
+
end
|
|
1992
|
+
end
|
|
1993
|
+
if redis.call('ZADD', prefix .. lane, now, key) == 1 then
|
|
1994
|
+
redis.call('INCRBY', prefix .. 'bytes:' .. lane, size)
|
|
1995
|
+
end
|
|
1996
|
+
end
|
|
1997
|
+
|
|
1998
|
+
local function held(prefix, lane)
|
|
1999
|
+
return tonumber(redis.call('GET', prefix .. 'bytes:' .. lane) or '0')
|
|
2000
|
+
end
|
|
2001
|
+
|
|
2002
|
+
local function balance(prefix, kept, now, budget)
|
|
2003
|
+
while held(prefix, 'protected') > budget * 0.8 do
|
|
2004
|
+
local oldest = redis.call('ZRANGE', prefix .. 'protected', 0, 0)[1]
|
|
2005
|
+
if not oldest or oldest == kept then break end
|
|
2006
|
+
place(prefix, oldest, 'probation', now)
|
|
2007
|
+
end
|
|
2008
|
+
while held(prefix, 'probation') + held(prefix, 'protected') > budget do
|
|
2009
|
+
local victim
|
|
2010
|
+
for _, lane in ipairs(LANES) do
|
|
2011
|
+
for _, key in ipairs(redis.call('ZRANGE', prefix .. lane, 0, 1)) do
|
|
2012
|
+
if key ~= kept then
|
|
2013
|
+
victim = key
|
|
2014
|
+
break
|
|
2015
|
+
end
|
|
2016
|
+
end
|
|
2017
|
+
if victim then break end
|
|
2018
|
+
end
|
|
2019
|
+
if not victim then break end
|
|
2020
|
+
evict(prefix, victim)
|
|
2021
|
+
end
|
|
2022
|
+
end
|
|
2023
|
+
`;
|
|
2024
|
+
var SET = `${LANES}
|
|
2025
|
+
local prefix, key, body, ttl, where, now, budget = KEYS[1], ARGV[1], ARGV[2], tonumber(ARGV[3]), ARGV[4], tonumber(ARGV[5]), tonumber(ARGV[6])
|
|
2026
|
+
local lane = 'probation'
|
|
2027
|
+
if redis.call('HEXISTS', prefix .. 'sizes', key) == 1 then
|
|
2028
|
+
lane = 'protected'
|
|
2029
|
+
evict(prefix, key)
|
|
2030
|
+
end
|
|
2031
|
+
local space = string.match(where, '^([^\\n]*)\\n')
|
|
2032
|
+
redis.call('SET', prefix .. 'page:' .. key, body, 'PX', ttl)
|
|
2033
|
+
redis.call('HSET', prefix .. 'where', key, where)
|
|
2034
|
+
redis.call('HSET', prefix .. 'sizes', key, string.len(body))
|
|
2035
|
+
redis.call('SADD', prefix .. 'space:' .. space, key)
|
|
2036
|
+
redis.call('SADD', prefix .. 'spaces', space)
|
|
2037
|
+
place(prefix, key, lane, now)
|
|
2038
|
+
for _, other in ipairs(LANES) do
|
|
2039
|
+
for _, gone in ipairs(redis.call('ZRANGEBYSCORE', prefix .. other, '-inf', now - ttl, 'LIMIT', 0, 32)) do
|
|
2040
|
+
evict(prefix, gone)
|
|
2041
|
+
end
|
|
2042
|
+
end
|
|
2043
|
+
balance(prefix, key, now, budget)
|
|
2044
|
+
return 1
|
|
2045
|
+
`;
|
|
2046
|
+
var TOUCH = `${LANES}
|
|
2047
|
+
local prefix, key, now, budget = KEYS[1], ARGV[1], tonumber(ARGV[2]), tonumber(ARGV[3])
|
|
2048
|
+
if redis.call('HEXISTS', prefix .. 'sizes', key) == 1 then
|
|
2049
|
+
place(prefix, key, 'protected', now)
|
|
2050
|
+
balance(prefix, key, now, budget)
|
|
2051
|
+
end
|
|
2052
|
+
return 1
|
|
2053
|
+
`;
|
|
2054
|
+
var INVALIDATE = `${LANES}
|
|
2055
|
+
local prefix, space, environment, host = KEYS[1], ARGV[1], ARGV[2], ARGV[3]
|
|
2056
|
+
local spaces
|
|
2057
|
+
if space ~= '' then spaces = { space } else spaces = redis.call('SMEMBERS', prefix .. 'spaces') end
|
|
2058
|
+
local count = 0
|
|
2059
|
+
for _, id in ipairs(spaces) do
|
|
2060
|
+
for _, key in ipairs(redis.call('SMEMBERS', prefix .. 'space:' .. id)) do
|
|
2061
|
+
local env, at = string.match(redis.call('HGET', prefix .. 'where', key) or '', '^[^\\n]*\\n([^\\n]*)\\n(.*)$')
|
|
2062
|
+
if (environment == '' or env == environment) and (host == '' or at == host) then
|
|
2063
|
+
count = count + evict(prefix, key)
|
|
2064
|
+
end
|
|
2065
|
+
end
|
|
2066
|
+
end
|
|
2067
|
+
return count
|
|
2068
|
+
`;
|
|
2069
|
+
var ENCODINGS = [
|
|
2070
|
+
"br",
|
|
2071
|
+
"gzip",
|
|
2072
|
+
"identity"
|
|
2073
|
+
];
|
|
2074
|
+
/**
|
|
2075
|
+
* `<encoding>:<renderedAt>:<script nonce>:` and the body's bytes, as they are: one value, no base64 on a page of a
|
|
2076
|
+
* hundred KB. The nonce is base64, which has no `:` in it.
|
|
2077
|
+
*/
|
|
2078
|
+
var envelope = ({ encoding, body, renderedAt, nonce }) => Buffer.concat([Buffer.from(`${encoding}:${renderedAt}:${nonce}:`, "utf-8"), body]);
|
|
2079
|
+
var unwrap = (value) => {
|
|
2080
|
+
const first = value.indexOf(":");
|
|
2081
|
+
const second = first < 0 ? -1 : value.indexOf(":", first + 1);
|
|
2082
|
+
const third = second < 0 ? -1 : value.indexOf(":", second + 1);
|
|
2083
|
+
if (third < 0) return;
|
|
2084
|
+
const encoding = ENCODINGS.find((name) => name === value.subarray(0, first).toString("utf-8"));
|
|
2085
|
+
const renderedAt = Number(value.subarray(first + 1, second).toString("utf-8"));
|
|
2086
|
+
if (!encoding || !Number.isFinite(renderedAt)) return;
|
|
2087
|
+
return {
|
|
2088
|
+
encoding,
|
|
2089
|
+
renderedAt,
|
|
2090
|
+
nonce: value.subarray(second + 1, third).toString("utf-8"),
|
|
2091
|
+
body: value.subarray(third + 1)
|
|
2092
|
+
};
|
|
2093
|
+
};
|
|
2094
|
+
/**
|
|
2095
|
+
* The pages every replica of a deployment shares, in the Redis it already runs (`cache.store`). Each page is filed
|
|
2096
|
+
* under its space, so `server.cache.invalidate({ spaceId })` drops exactly that space's — on every replica at once,
|
|
2097
|
+
* since they all read here. A value that is not one this store wrote reads as no page.
|
|
2098
|
+
*/
|
|
2099
|
+
var createRedisPageStore = (client, { prefix = "plitzi:{pages}:", maxBytes = bytesFromEnvironment(CACHE_ENV.storeMaxBytes) ?? DEFAULT_CACHE_BYTES.store } = {}) => ({
|
|
2100
|
+
get: async (key) => {
|
|
2101
|
+
const value = await client.getBuffer(`${prefix}page:${key}`);
|
|
2102
|
+
const page = value ? unwrap(value) : void 0;
|
|
2103
|
+
if (page) client.eval(TOUCH, 1, prefix, key, Date.now(), maxBytes).catch((error) => {
|
|
2104
|
+
serverLog.debug("SSR cache", "A shared page was read but not marked as used", error);
|
|
2105
|
+
});
|
|
2106
|
+
return page;
|
|
2107
|
+
},
|
|
2108
|
+
set: async (key, page, { spaceId, environment, hostname }, ttlMs) => {
|
|
2109
|
+
const body = envelope(page);
|
|
2110
|
+
if (body.length > maxBytes) return;
|
|
2111
|
+
await client.eval(SET, 1, prefix, key, body, Math.max(1, Math.round(ttlMs)), `${String(spaceId)}\n${environment}\n${hostname}`, Date.now(), maxBytes);
|
|
2112
|
+
},
|
|
2113
|
+
invalidate: async (filter = {}) => {
|
|
2114
|
+
const count = await client.eval(INVALIDATE, 1, prefix, filter.spaceId === void 0 ? "" : String(filter.spaceId), filter.environment ?? "", filter.hostname ?? "");
|
|
2115
|
+
return typeof count === "number" ? count : 0;
|
|
2116
|
+
}
|
|
2117
|
+
});
|
|
2118
|
+
export { visitorScheme as $, shareCache as A, renderLimitOf as B, createOfflineDataLoader as C, cacheLimitsOf as D, normalizePlugins as E, offlineDataWith as F, buildCacheManager as G, keepPage as H, spaceDocument as I, keepsVersion as J, buildHtmlCacheKey as K, styleSheetOf as L, destroyServerCaches as M, digest as N, cacheFilterOf as O, hydrationPayload as P, SCHEME_HINT_HEADER as Q, DEFAULT_RENDER_WAIT_MS as R, sendScriptPolicy as S, normalizePluginSource as T, pageHtml as U, fromSharedPage as V, toSharedPage as W, ignoredQueryParamsOf as X, offlineDataCacheKeyOf as Y, renderedQuery as Z, buildServerInfo as _, presentsCredential as a, CSP_REPORT_PATH as b, wildcardSubdomain as c, createAuthAdapters as d, readCookie as et, createJsonAdapters as f, resolveDebugMode as g, escapeHtml as h, fixedSpace as i, requestPaintedState as it, createServerCaches as j, createCacheInvalidator as k, createMemoryCache as l, RequestMetrics as m, createSpaceAdapters as n, DEFAULT_IGNORED_QUERY_PARAMS as nt, renderGrant as o, createCloudAdapters as p, buildRscCacheKey as q, authoringPreview as r, DEFAULT_TTL_MS as rt, verifiedDomain as s, createRedisPageStore as t, DEFAULT_CACHE_BYTES as tt, refuse as u, googleFontsStage as v, reportReactBuild as w, scriptTemplateParams as x, googleFontsUrlOf as y, renderLimitFor as z };
|