Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(cdp): client side destinations #26169

Draft
wants to merge 3 commits into
base: hog-to-js
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 45 additions & 1 deletion posthog/api/site_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@
from statshog.defaults.django import statsd

from posthog.exceptions import generate_exception_response
from posthog.hogql import ast
from posthog.hogql.compiler.javascript import JavaScriptCompiler
from posthog.hogql.parser import parse_string_template
from posthog.logging.timing import timed
from posthog.plugins.site import get_site_config_from_schema, get_transpiled_site_source

Expand All @@ -22,7 +25,48 @@ def get_site_app(request: HttpRequest, id: int, token: str, hash: str) -> HttpRe
id = source_file.id
source = source_file.source
config = get_site_config_from_schema(source_file.config_schema, source_file.config)
response = f"{source}().inject({{config:{json.dumps(config)},posthog:window['__$$ph_site_app_{id}']}})"

# Wrap in IIFE = Immediately Invoked Function Expression = to avoid polluting global scope
response = "(function() {\n\n"

# Build a switch statement within a try/catch loop and a static dict
config_switch = ""
config_dict_items: list[str] = []

compiler = JavaScriptCompiler()
for key, value in config.items():
key_string = json.dumps(str(key) or "<empty>")
if isinstance(value, str) and "{" in value:
base_code = compiler.visit(ast.ReturnStatement(expr=parse_string_template(value)))
config_switch += f"case {key_string}: {base_code};\n"
config_dict_items.append(f"{key_string}: getConfigKey({json.dumps(key)}, initial)")
else:
config_dict_items.append(f"{key_string}: {json.dumps(value)}")

# Start with the STL functions
response += compiler.get_inlined_stl() + "\n"

# This will be used by Hog code to access globals
response += "let __globals = {};\n"
response += "function __getGlobal(key) { return __globals[key] }\n"

if config_switch:
response += (
f"function getConfigKey(key, initial) {{ try {{ switch (key) {{\n\n///// calculated properties\n"
)
response += config_switch
response += "\ndefault: return null; }\n"
response += "} catch (e) { if(!initial) {console.warn('[POSTHOG-JS] Unable to get config field', key, e);} return null } }\n"

response += (
f"function getConfig(globals, initial) {{ __globals = globals || {'{}'}; return {{\n\n///// config\n"
)
response += ",\n".join(config_dict_items)
response += "\n\n} }\n"

response += f"{source}().inject({{config:getConfig({'{}'}, true),getConfig:getConfig,posthog:window['__$$ph_site_app_{id}']}});"

response += "\n\n})();"

statsd.incr(f"posthog_cloud_raw_endpoint_success", tags={"endpoint": "site_app"})
return HttpResponse(content=response, content_type="application/javascript")
Expand Down
7 changes: 5 additions & 2 deletions posthog/hogql/compiler/javascript.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
from posthog.hogql.visitor import Visitor

# TODO: make sure _JS_GET_GLOBAL is unique!
_JS_GET_GLOBAL = "get_global"
_JS_GET_GLOBAL = "__getGlobal"
_JS_KEYWORDS = ["var", "let", "const", "function", "typeof", "Error"]


Expand Down Expand Up @@ -52,7 +52,7 @@
supported_functions = supported_functions or set()
compiler = JavaScriptCompiler(supported_functions, args, context, in_repl, locals)
base_code = compiler.visit(expr)
import_code = import_stl_functions(compiler.inlined_stl)
import_code = compiler.get_inlined_stl()
code = import_code + ("\n\n" if import_code else "") + base_code
return CompiledJavaScript(code=code, locals=compiler.locals)

Expand Down Expand Up @@ -89,12 +89,15 @@
self.args = args or []
self.context = context or HogQLContext(team_id=None)
self.indent_level = 0
self.inlined_stl = set()

Check failure on line 92 in posthog/hogql/compiler/javascript.py

View workflow job for this annotation

GitHub Actions / Python code quality checks

Need type annotation for "inlined_stl" (hint: "inlined_stl: set[<type>] = ...")

# Initialize locals with function arguments
for arg in self.args:
self._declare_local(arg)

def get_inlined_stl(self) -> str:
return import_stl_functions(self.inlined_stl)

def _start_scope(self):
self.scope_depth += 1

Expand Down Expand Up @@ -199,10 +202,10 @@
for index, element in enumerate(node.chain):
if index == 0:
if found_local:
array_code = _sanitize_var_name(element)

Check failure on line 205 in posthog/hogql/compiler/javascript.py

View workflow job for this annotation

GitHub Actions / Python code quality checks

Argument 1 to "_sanitize_var_name" has incompatible type "str | int"; expected "str"
elif element in STL_FUNCTIONS:
self.inlined_stl.add(element)
array_code = f"{_sanitize_var_name(element)}"

Check failure on line 208 in posthog/hogql/compiler/javascript.py

View workflow job for this annotation

GitHub Actions / Python code quality checks

Argument 1 to "_sanitize_var_name" has incompatible type "str | int"; expected "str"
else:
array_code = f"{_JS_GET_GLOBAL}({json.dumps(element)})"
continue
Expand Down Expand Up @@ -441,7 +444,7 @@
array_code = ""
for index, element in enumerate(chain):
if index == 0:
array_code = _sanitize_var_name(element)

Check failure on line 447 in posthog/hogql/compiler/javascript.py

View workflow job for this annotation

GitHub Actions / Python code quality checks

Argument 1 to "_sanitize_var_name" has incompatible type "str | int"; expected "str"
if len(chain) == 1:
array_code = f"{array_code} = {self.visit(node.right)}"
elif (isinstance(element, int) and not isinstance(element, bool)) or isinstance(element, str):
Expand Down
Loading