-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: add worker to provide Prophet script (#143)
Co-authored-by: deepsource-autofix[bot] <62050782+deepsource-autofix[bot]@users.noreply.github.com>
- Loading branch information
1 parent
3a7f018
commit ab2b0d5
Showing
36 changed files
with
6,650 additions
and
5,586 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
node_modules | ||
dist | ||
.wrangler | ||
.dev.vars | ||
|
||
# Change them to your taste: | ||
package-lock.json | ||
yarn.lock | ||
pnpm-lock.yaml | ||
bun.lockb |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,8 @@ | ||
``` | ||
yarn install | ||
yarn run dev | ||
``` | ||
|
||
``` | ||
yarn run deploy | ||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,15 @@ | ||
tasks: | ||
deploy: | ||
command: | ||
- wrangler | ||
- deploy | ||
- --minify | ||
- src/index.ts | ||
platform: node | ||
dev: | ||
command: | ||
- wrangler | ||
- dev | ||
- src/index.ts | ||
local: true | ||
platform: node |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
{ | ||
"name": "script-provider", | ||
"scripts": { | ||
"dev": "moon run dev", | ||
"deploy": "moon run deploy" | ||
}, | ||
"dependencies": { | ||
"@ts-rest/core": "^3.41.0", | ||
"@urql/core": "^5.0.0", | ||
"effect": "^2.4.18", | ||
"esbuild-wasm": "^0.20.2", | ||
"hono": "^4.2.2", | ||
"proper-tags": "^2.0.2", | ||
"ts-pattern": "^5.1.0", | ||
"ufo": "^1.5.3" | ||
}, | ||
"devDependencies": { | ||
"@cloudflare/workers-types": "^4.20240404.0", | ||
"wrangler": "^3.47.1" | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,86 @@ | ||
import { Hono } from 'hono' | ||
import { oneLineTrim } from 'proper-tags' | ||
import { Effect, SynchronizedRef, pipe } from 'effect' | ||
import esbuild from 'esbuild-wasm' | ||
import { SiteSubscriptionInfo } from 'storipress-client' | ||
// ref: https://blog.interactions.rest/blog/esbuild-on-the-edge/ | ||
// @ts-expect-error no type | ||
// eslint-disable-next-line antfu/no-import-node-modules-by-path | ||
import wasm from '../../../node_modules/esbuild-wasm/esbuild.wasm' | ||
import { GraphqlService } from './services/GraphqlService' | ||
|
||
const PRODUCTION_URL = 'https://assets.stori.press/storipress/leaky-paywall.min.js' | ||
const CONFIG_VAR_NAME = 'SP_PAYWALL' | ||
|
||
// @ts-expect-error polyfill | ||
globalThis.performance = Date | ||
|
||
const javascript = oneLineTrim | ||
|
||
const app = new Hono() | ||
|
||
app.get('/', (c) => { | ||
return c.text('Not found', 404) | ||
}) | ||
|
||
const initializedRef = SynchronizedRef.unsafeMake(false) | ||
|
||
app.get('/:clientId/prophet.js', (c) => { | ||
const clientId = c.req.param('clientId') | ||
|
||
return pipe( | ||
SynchronizedRef.updateEffect(initializedRef, () => | ||
pipe( | ||
Effect.promise(() => | ||
esbuild.initialize({ | ||
wasmModule: wasm, | ||
worker: false, | ||
}), | ||
), | ||
Effect.as(true), | ||
), | ||
), | ||
Effect.flatMap(() => | ||
pipe( | ||
GraphqlService, | ||
Effect.flatMap(({ query }) => query(SiteSubscriptionInfo, {})), | ||
Effect.flatMap((res) => { | ||
const config = JSON.stringify({ | ||
flags: { | ||
paywall: true, | ||
tracking: true, | ||
}, | ||
freeLimit: 3, | ||
pathPattern: null, | ||
all: false, | ||
clientId, | ||
logo: '', | ||
title: res.data?.siteSubscriptionInfo.name ?? 'Welcome', | ||
description: res.data?.siteSubscriptionInfo.description ?? '', | ||
// TODO: need primary color config | ||
primaryColor: 'rgb(29 78 216)', | ||
}) | ||
const code = javascript` | ||
window.${CONFIG_VAR_NAME} = ${config}; | ||
let s=document.createElement('script'); | ||
s.type='module'; | ||
s.src='${PRODUCTION_URL}'; | ||
document.head.append(s); | ||
` | ||
return Effect.promise(() => esbuild.transform(code, { loader: 'js', minify: true })) | ||
}), | ||
Effect.map((minified) => c.text(minified.code, 200, { 'content-type': 'text/javascript' })), | ||
), | ||
), | ||
Effect.provide(GraphqlService.layer(clientId)), | ||
Effect.catchTag('NotFoundError', () => Effect.succeed(c.text('Not Found', 404))), | ||
Effect.catchAll((error) => { | ||
// eslint-disable-next-line no-console | ||
console.log(error) | ||
return Effect.succeed(c.text('Internal Server Error', 500)) | ||
}), | ||
Effect.runPromise, | ||
) | ||
}) | ||
|
||
export default app |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,51 @@ | ||
import { Context, Effect, Inspectable, Layer, pipe } from 'effect' | ||
import type { AnyVariables, CombinedError, OperationResult, TypedDocumentNode } from '@urql/core' | ||
import { Client, cacheExchange, fetchExchange } from '@urql/core' | ||
import { joinURL } from 'ufo' | ||
import { createClient } from '../utils/rest-client' | ||
import { getApiHostUrl, getEnvironmentFromClientId } from '../utils/api-host-url' | ||
import { GraphqlError, NotFoundError } from '../utils/errors' | ||
|
||
interface GraphqlServiceImpl { | ||
query: <Data, Variables extends AnyVariables>( | ||
document: TypedDocumentNode<Data, Variables>, | ||
variables: Variables, | ||
) => Effect.Effect<OperationResult<Data, Variables>, GraphqlError> | ||
} | ||
|
||
export class GraphqlService extends Context.Tag('@app/GraphqlService')<GraphqlService, GraphqlServiceImpl>() { | ||
static layer = (clientId: string) => { | ||
const env = getEnvironmentFromClientId(clientId) | ||
const restClient = createClient(env) | ||
|
||
return Layer.effect( | ||
this, | ||
pipe( | ||
Effect.promise(() => restClient.getTenantState({ params: { clientId } })), | ||
Effect.tap((res) => Effect.log(`check ${clientId} state: ${Inspectable.format(res.body)}`)), | ||
Effect.filterOrFail( | ||
(res) => res.status === 200 && res.body.state === 'online', | ||
() => new NotFoundError(), | ||
), | ||
Effect.map(() => { | ||
const client = new Client({ | ||
url: joinURL(getApiHostUrl(env), `/client/${clientId}/graphql`), | ||
exchanges: [cacheExchange, fetchExchange], | ||
}) | ||
|
||
return GraphqlService.of({ | ||
query: (document, variables) => { | ||
return pipe( | ||
Effect.promise(() => client.query(document, variables)), | ||
Effect.filterOrFail( | ||
(res) => res.error === undefined, | ||
(res) => new GraphqlError({ cause: res.error as CombinedError }), | ||
), | ||
) | ||
}, | ||
}) | ||
}), | ||
), | ||
) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
import { z } from 'zod' | ||
import { P, match } from 'ts-pattern' | ||
|
||
export const EnvironmentSchema = z.enum(['production', 'staging', 'development']) | ||
|
||
export type Environment = z.infer<typeof EnvironmentSchema> | ||
|
||
export function getEnvironmentFromClientId(clientId: string): Environment { | ||
return match(clientId) | ||
.returnType<Environment>() | ||
.with(P.string.startsWith('P'), () => 'production') | ||
.with(P.string.startsWith('S'), () => 'staging') | ||
.with(P.string.startsWith('D'), () => 'development') | ||
.otherwise(() => 'development') | ||
} | ||
|
||
const apiHostMap: Record<Environment, string> = { | ||
production: 'https://api.stori.press', | ||
staging: 'https://api.storipress.pro', | ||
development: 'https://api.storipress.dev', | ||
} | ||
|
||
export function getApiHostUrl(environment: Environment): string { | ||
return apiHostMap[environment] | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
import type { CombinedError } from '@urql/core' | ||
import { Data } from 'effect' | ||
|
||
export class NotFoundError extends Data.TaggedError('NotFoundError') {} | ||
|
||
export class GraphqlError extends Data.TaggedError('GraphqlError')<{ cause: CombinedError }> {} |
Oops, something went wrong.