How to use fp-ts-contrib - 10 common examples

To help you get started, we’ve selected a few fp-ts-contrib examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github rzeigler / waveguide / test / semaphore.spec.ts View on Github external
it("should block acquisition", () => {
    const eff = Do(io.instances)
      .bind("gate", makeRef(false))
      .bind("sem", makeSemaphore(0))
      .doL(({gate, sem}) => io.fork(sem.withPermit(gate.set(true))))
      .bindL("before", ({gate}) => gate.get)
      .doL(({sem}) => sem.release)
      .do(io.shifted) // let the forked fiber advance
      .bindL("after", ({gate, sem}) => io.zip(gate.get, sem.available))
      .return(({before, after}) => [before, ...after]);
    return expectExit(eff, done([false, true, 1]));
  });
  it("should allow acquire to be interruptible", () => {
github mikearnaldi / matechs-effect / packages / effect / type-tests / Effect.ts View on Github external
type R2 = EnvOf<{ a: Env1String; b: UString }>; // $ExpectType Env1
//@ts-ignore
type R3 = EnvOf<{ a: NeverString; b: UString }>; // $ExpectType unknown
//@ts-ignore
type R4 = EnvOf<{ a: Env1String; b: Env2String }>; // $ExpectType Env1 & Env2
//@ts-ignore
type ATypeOfU = ATypeOf; // $ExpectType string
//@ts-ignore
type ATypeOfO = ATypeOf; // $ExpectType string
//@ts-ignore
type ATypeOfNever = ATypeOf; // $ExpectType string

const M = _.effect;

//@ts-ignore
const doAErr = Do(M) // $ExpectType Effect
  .bindL("x", () => _.accessM(({}: Env2) => M.of("a")))
  .sequenceS({
    a: _.accessM(({}: Env1) => M.throwError("a")),
    b: M.throwError("b")
  })
  .return(r => r);

//@ts-ignore
const doA = Do(M) // $ExpectType Effect
  .bindL("x", () => _.accessM(({}: Env2) => M.of("a")))
  .sequenceS({
    a: _.accessM(({}: Env1) => M.of("a")),
    b: M.of(2)
  })
  .return(r => r);
github mikearnaldi / matechs-effect / packages / effect / src / stream / index.ts View on Github external
function attach(
          action: T.Effect
        ): T.Effect {
          return (
            Do(T.effect)
              .bindL("next", () => cell.update(n => n + 1))
              .bind("fiber", T.fork(action))
              .doL(({ next, fiber }) =>
                store.update(handles => [...handles, [next, fiber] as const])
              )
              // Spawn a fiber that will cleanup the handle reference on complete
              .doL(({ next, fiber }) =>
                T.fork(
                  T.applySecond(
                    fiber.wait,
                    store.update(array.filter(h => h[0] !== next))
                  )
                )
              )
              .return(constant(undefined as void))
          );
github mikearnaldi / matechs-effect / packages / rpc / demo / server.ts View on Github external
// implement the service
export const placeholderJsonLive = F.implement(placeholderJsonM)({
  [placeholderJsonEnv]: {
    getTodo: n =>
      pipe(
        H.get(`https://jsonplaceholder.typicode.com/todos/${n}`),
        T.chainError(() => T.raiseError("error fetching todo")),
        T.map(({ body }) => body),
        authenticated
      )
  }
});

// create a new express server
const program = EX.withApp(
  Do(T.effect)
    .do(RPC.server(placeholderJsonM, placeholderJsonLive)) // wire module to express
    .bind("server", EX.bind(8081)) // listen on port 8081
    .return(s => s.server) // return node server
);

// construct live environment
const envLive: Env = {
  ...EX.express,
  ...L.libcurl(),
  ...H.jsonDeserializer,
  [RPC.serverConfigEnv]: {
    [placeholderJsonEnv]: {
      scope: "/placeholderJson" // exposed at /placeholderJson
    }
  }
};
github SamHH / bukubrow-webext / src / modules / comms / browser.ts View on Github external
const browserTabsQuery = (x: Tabs.QueryQueryInfoType): TaskOption> =>
	TO.tryCatch(() => browser.tabs.query(x));

export const getActiveTab: TaskOption = pipe(
	browserTabsQuery({ active: true, currentWindow: true }),
	TO.chainOption(A.head),
);

export const getActiveWindowTabs: TaskOption> = pipe(
	browserTabsQuery({ currentWindow: true }),
	TO.chainOption(NEA.fromArray),
);

export const getAllTabs: TaskOption> = pipe(
	browserTabsQuery({}),
	TO.chainOption(NEA.fromArray),
);

export const onTabActivity = (cb: Lazy): void => {
	browser.tabs.onActivated.addListener(cb);
	browser.tabs.onUpdated.addListener(cb);
};

// The imperfect title includes check is because Firefox's href changes
// according to the extension in use, if any
const isNewTabPage: Predicate> = ({ url = '', title = '' }) =>
	['about:blank', 'chrome://newtab/'].includes(url) || title.includes('New Tab');

/// The active tab will not update quickly enough to allow this function to be
/// called safely in a loop. Therefore, the second argument forces consumers to
/// verify that this is only the first tab they're opening.
export const openBookmarkInAppropriateTab = (isFirstTab: boolean) => (url: string): Task => pipe(
github rzeigler / waveguide / test / queue.spec.ts View on Github external
(ops, queueSize, delayWrite, delayRead) =>
          io.runToPromise(Do(io.instances)
            .bind("q", boundedQueue(queueSize))
            .bindL("writeFiber",
              ({q}) =>
                pipe(
                  array.traverse(io.instances)(ops, ([v, d]) =>
                    io.delay(q.offer(v), d)),
                  io.liftDelay(delayWrite),
                  io.fork
                )
            )
            .bindL("readFiber",
              ({q}) =>
                pipe(
                  array.traverse(io.instances)(ops,
                    ([v, _, d]) => io.delay(io.chain(q.take, assertStringEq(v)), d)),
                  io.liftDelay(delayRead),
github DenisFrezzato / hyper-ts-fastify / test / index.ts View on Github external
        E.map(([a, cout]) => [a, L.toReversedArray((cout as MockConnection).actions)]),
      ),
github mikearnaldi / matechs-effect / src / example / Main.ts View on Github external
import { Do } from "fp-ts-contrib/lib/Do";
import { pipe } from "fp-ts/lib/pipeable";
import { withControllerSpan, withTracer } from "./Tracer";

export const module = pipe(
  E.noEnv,
  E.mergeEnv(P.printer),
  E.mergeEnv(C.counter),
  E.mergeEnv(T.tracer),
  E.mergeEnv(T.tracerFactoryDummy)
);

export const program = withTracer(
  E.provide(C.counterState())(
    Do(E.effectMonad)
      .bind("start", C.currentCount())
      .do(withControllerSpan("controller-a")(C.count()))
      .do(withControllerSpan("controller-b")(C.count()))
      .bind("end", C.currentCount())
      .doL(({ start, end }) => P.print(`done - ${start} <-> ${end}`))
      .done()
  )
);

export const main = E.run(pipe(program, E.provide(module)));
github mikearnaldi / matechs-effect / packages / tracing / src / index.ts View on Github external
withTracer(
      ma: T.Effect
    ): T.Effect {
      return Do(T.effect)
        .bind("instance", factory)
        .bindL("res", ({ instance }) =>
          T.provideR((r: R) => ({
            ...r,
            tracer: {
              ...(r as any)["tracer"],
              context: { tracerInstance: instance }
            }
          }))(ma)
        )
        .return(s => s.res);
    },
    withControllerSpan(
github mikearnaldi / matechs-effect / packages / rpc / src / index.ts View on Github external
if (typeof x[z] === "function") {
        r[z] = (...args: any[]) =>
          Do(T.effect)
            .bindL("req", () => T.pure({ args }))
            .bindL("con", () => T.access((c: ClientConfig) => c))
            .bindL("res", ({ con, req }) =>
              H.post(`${con[clientConfigEnv][entry].baseUrl}/${z}`, req)
            )
            .bindL("ret", ({ res }) =>
              isSome(res.body)
                ? T.completed((res.body.value as RPCResponse).value)
                : T.raiseError(new Error("empty response"))
            )
            .return(s => s.ret);
      } else if (typeof x[z] === "object") {
        r[z] = Do(T.effect)
          .bindL("req", () => T.pure({ args: [] }))
          .bindL("con", () => T.access((c: ClientConfig) => c))
          .bindL("res", ({ con, req }) =>
            H.post(`${con[clientConfigEnv][entry].baseUrl}/${z}`, req)
          )
          .bindL("ret", ({ res }) =>
            isSome(res.body)
              ? T.completed((res.body.value as RPCResponse).value)
              : T.raiseError(new Error("empty response"))
          )
          .return(s => s.ret);
      }
    }
  }

  return r;