# SPDX-FileCopyrightText: ☭ Emery Hemingway # SPDX-License-Identifier: Unlicense import std/[re, tables, uri] import preserves, syndicate, syndicate/patterns import ./protocol, ./common # importing std/re doesn't actually link against PCRE {.passC: staticExec("pkg-config --cflags libpcre").} {.passL: staticExec("pkg-config --libs libpcre").} type RegexAction = tuple[regex: Regex, entity: Ref, action: Assertion] proc rewrite(result: var Assertion; uri: string; regex: Regex) = proc op(pr: var Assertion) = if pr.isString: pr.string = replacef(uri, regex, pr.string) apply(result, op) runActor("main") do (root: Ref; turn: var Turn): connectStdio(root, turn) var handlers: Table[Handle, RegexAction] during(turn, root, ?UriRunnerConfig) do (handlerspace: Ref, urispace: Ref): during(turn, handlerspace, dropType(ActionHandler)) do: during(turn, handlerspace, ?ActionHandler) do (pat: string; entity: Ref; act: Assertion): # `duringHandle` is a symbol exposed by the `during` macro handlers[duringHandle] = (re(pat, {reIgnoreCase, reStudy}), entity, act,) do: del(handlers, duringHandle) onMessage(turn, urispace, Open ? {0:grab()}) do (u: uri.Uri): let uri = $u assert len(handlers) > 0 var matched = false for handler in handlers.values: if match(uri, handler.regex): matched = true var action = handler.action try: rewrite(action, uri, handler.regex) message(turn, handler.entity, action) except CatchableError: stderr.writeLine "rewrite failed on ", action if not matched: stderr.writeLine "no actions matched for ", uri do: clear(handlers)