🚀 Big News: Socket Acquires Coana to Bring Reachability Analysis to Every Appsec Team.Learn more
Socket
DemoInstallSign in
Socket

@pbinj/pbj

Package Overview
Dependencies
Maintainers
1
Versions
17
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@pbinj/pbj - npm Package Compare versions

Comparing version

to
3.0.0

22

dist/cjs/context.js

@@ -6,3 +6,3 @@ "use strict";

exports.createNewContext = createNewContext;
const guards_js_1 = require("./guards.js");
const pbj_guards_1 = require("@pbinj/pbj-guards");
const errors_js_1 = require("./errors.js");

@@ -22,5 +22,5 @@ const ServiceDescriptor_js_1 = require("./ServiceDescriptor.js");

}
onServiceAdded(fn, intitialize = true) {
onServiceAdded(fn, initialize = true) {
this.logger.info("onServiceAdded: listener added");
if (intitialize) {
if (initialize) {
for (const service of this.map.values()) {

@@ -44,6 +44,6 @@ for (const fn of this.listeners) {

const key = (0, util_js_1.keyOf)(service);
if ((0, guards_js_1.isFn)(fn)) {
if ((0, pbj_guards_1.isFn)(fn)) {
this._visit(key, fn);
}
else if ((0, guards_js_1.isFn)(service)) {
else if ((0, pbj_guards_1.isFn)(service)) {
for (const key of this.map.keys()) {

@@ -105,3 +105,3 @@ this._visit(key, service);

let args = [...origArgs];
if ((0, guards_js_1.isSymbol)(serviceKey)) {
if ((0, pbj_guards_1.isSymbol)(serviceKey)) {
service = args.shift();

@@ -123,3 +123,3 @@ }

}
const newInst = new ServiceDescriptor_js_1.ServiceDescriptor(serviceKey, service, args, true, (0, guards_js_1.isFn)(service), undefined, () => {
const newInst = new ServiceDescriptor_js_1.ServiceDescriptor(serviceKey, service, args, true, (0, pbj_guards_1.isFn)(service), undefined, () => {
this.invalidate(key);

@@ -142,4 +142,4 @@ }, this.logger.createChild((0, pbjKey_js_1.asString)(serviceKey)));

}
resolve(tkey, ...args) {
return this.register(tkey, ...args).invoke();
resolve(typeKey, ...args) {
return this.register(typeKey, ...args).invoke();
}

@@ -159,4 +159,4 @@ newContext() {

}
else if ((0, guards_js_1.isFn)(service)) {
if ((0, guards_js_1.isConstructor)(service)) {
else if ((0, pbj_guards_1.isFn)(service)) {
if ((0, pbj_guards_1.isConstructor)(service)) {
yield* (0, util_js_1.filterMap)(this.map.values(), (v) => (0, util_js_1.isInherited)(v.service, service) ? v.proxy : undefined);

@@ -163,0 +163,0 @@ }

@@ -6,3 +6,3 @@ "use strict";

exports.isAsyncError = isAsyncError;
const guards_js_1 = require("./guards.js");
const pbj_guards_1 = require("@pbinj/pbj-guards");
const pbjKey_js_1 = require("./pbjKey.js");

@@ -22,3 +22,3 @@ const symbol = Symbol("@pbj/ServiceDescriptorProxy");

function isAsyncError(e) {
return (0, guards_js_1.has)(e, symbol) && e[symbol] === true;
return (0, pbj_guards_1.has)(e, symbol) && e[symbol] === true;
}

@@ -25,0 +25,0 @@ class PBinJError extends Error {

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.nullableSymbol = void 0;
exports.isSymbol = isSymbol;
exports.isFn = isFn;
exports.isService = isService;
exports.isConstructor = isConstructor;
exports.isObjectish = isObjectish;
exports.has = has;
exports.hasA = hasA;
exports.isPrimitive = isPrimitive;
exports.isPrimitiveType = isPrimitiveType;
exports.isPBinJ = isPBinJ;
exports.isBoolean = isBoolean;
exports.isNullish = isNullish;
const symbols_js_1 = require("./symbols.js");
function isSymbol(x) {
return typeof x === "symbol";
}
function isFn(x) {
return typeof x === "function";
}
function isService(x) {
return hasA(x, symbols_js_1.serviceSymbol, isSymbol);
}
function isConstructor(x) {
return !!x.prototype && !!x.prototype.constructor.name;
}
function isObjectish(x) {
switch (typeof x) {
case "object":
case "function":
return x != null;
default:
return false;
}
}
function has(x, k) {
return isObjectish(x) && k in x;
}
function hasA(x, k, guard) {
return has(x, k) ? guard(x[k]) : false;
}
function isPrimitive(v) {
return (typeof v === "string" ||
typeof v === "number" ||
typeof v === "boolean" ||
typeof v === "symbol" ||
typeof v === "bigint");
}
function isPrimitiveType(v) {
return (v === String ||
v === Number ||
v === Boolean ||
v === Symbol ||
v === BigInt);
}
const pbj_guards_1 = require("@pbinj/pbj-guards");
function isPBinJ(v) {
return hasA(v, symbols_js_1.proxyKey, isSymbol);
return (0, pbj_guards_1.hasA)(v, symbols_js_1.proxyKey, pbj_guards_1.isSymbol);
}
exports.nullableSymbol = Symbol("@pbj/nullable");
function isBoolean(v) {
return typeof v === "boolean";
}
function isNullish(v) {
var _a;
return v == null || hasA(v, exports.nullableSymbol, isBoolean)
? ((_a = v === null || v === void 0 ? void 0 : v.nullable) !== null && _a !== void 0 ? _a : false)
return v == null || (0, pbj_guards_1.hasA)(v, exports.nullableSymbol, pbj_guards_1.isBoolean)
? ((_a = v === null || v === void 0 ? void 0 : v[exports.nullableSymbol]) !== null && _a !== void 0 ? _a : false)
: false;
}

@@ -6,2 +6,3 @@ "use strict";

const guards_js_1 = require("./guards.js");
const pbj_guards_1 = require("@pbinj/pbj-guards");
const symbols_js_1 = require("./symbols.js");

@@ -78,6 +79,6 @@ function newProxy(key, service) {

function isServiceDescriptor(v) {
return (0, guards_js_1.has)(v, symbols_js_1.serviceSymbol);
return (0, pbj_guards_1.has)(v, symbols_js_1.serviceSymbol);
}
const serviceDescriptor = (v) => {
if ((0, guards_js_1.hasA)(v, symbols_js_1.serviceDescriptorKey, isServiceDescriptor)) {
if ((0, pbj_guards_1.hasA)(v, symbols_js_1.serviceDescriptorKey, isServiceDescriptor)) {
return v[symbols_js_1.serviceDescriptorKey];

@@ -84,0 +85,0 @@ }

@@ -8,2 +8,3 @@ "use strict";

const symbols_js_1 = require("./symbols.js");
const pbj_guards_1 = require("@pbinj/pbj-guards");
const pbjKeyMap = new WeakMap();

@@ -32,6 +33,6 @@ const anonymousMap = new WeakMap();

}
if ((0, guards_js_1.isFn)(key)) {
if ((0, pbj_guards_1.isFn)(key)) {
return key.name || anonymous(key);
}
if ((0, guards_js_1.isSymbol)(key)) {
if ((0, pbj_guards_1.isSymbol)(key)) {
return key.description;

@@ -38,0 +39,0 @@ }

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const node_async_hooks_1 = require("node:async_hooks");
const guards_js_1 = require("./guards.js");
const pbj_guards_1 = require("@pbinj/pbj-guards");
const errors_js_1 = require("./errors.js");

@@ -19,3 +19,3 @@ const context_js_1 = require("./context.js");

*
* @param key - pkey or registry key
* @param key - typeKey or registry key
* @returns

@@ -25,7 +25,7 @@ */

const serviceDesc = this.register(key);
if ((0, guards_js_1.hasA)(serviceDesc, serviceProxySymbol, guards_js_1.isSymbol) &&
if ((0, pbj_guards_1.hasA)(serviceDesc, serviceProxySymbol, pbj_guards_1.isSymbol) &&
serviceDesc[serviceProxySymbol] !== (0, util_js_1.keyOf)(key)) {
throw new errors_js_1.PBinJError(`key ${String(key)} already registered as '${String(serviceDesc[serviceProxySymbol])}', can not register a key into more than one scope`);
}
if ((0, guards_js_1.has)(serviceDesc, asyncLocalSymbol)) {
if ((0, pbj_guards_1.has)(serviceDesc, asyncLocalSymbol)) {
throw new errors_js_1.PBinJError(`key ${String(key)} already registered as async scoped, can not register a key into more than one scope`);

@@ -42,3 +42,3 @@ }

if (!map.has(key)) {
map.set(key, new ServiceDescriptor_js_1.ServiceDescriptor(key, service, args, false, (0, guards_js_1.isFn)(service), `async scoped pbj '${String(key)}'`));
map.set(key, new ServiceDescriptor_js_1.ServiceDescriptor(key, service, args, false, (0, pbj_guards_1.isFn)(service), `async scoped pbj '${String(key)}'`));
}

@@ -45,0 +45,0 @@ return asyncLocalStorage.run(map, next);

@@ -11,3 +11,3 @@ "use strict";

const util_js_1 = require("./util.js");
const guards_js_1 = require("./guards.js");
const pbj_guards_1 = require("@pbinj/pbj-guards");
const newProxy_js_1 = require("./newProxy.js");

@@ -79,3 +79,3 @@ const symbols_js_1 = require("./symbols.js");

}
if (!(0, guards_js_1.isFn)(this.service)) {
if (!(0, pbj_guards_1.isFn)(this.service)) {
this.logger.error(`service '{service}' is not a function`, {

@@ -123,3 +123,3 @@ service: (0, pbjKey_js_1.asString)(this.service),

this.invoked = true;
this.primitive = (0, guards_js_1.isPrimitive)(resp);
this.primitive = (0, pbj_guards_1.isPrimitive)(resp);
if (resp == null && !this.optional) {

@@ -181,5 +181,5 @@ throw new errors_js_1.PBinJError(`service '${String(this[symbols_js_1.serviceSymbol])}' is not optional and returned null`);

this.invalidate();
this.invokable = (0, guards_js_1.isFn)(_service);
this.invokable = (0, pbj_guards_1.isFn)(_service);
this._service = _service;
this._factory = this.invokable && !(0, guards_js_1.isConstructor)(_service);
this._factory = this.invokable && !(0, pbj_guards_1.isConstructor)(_service);
this.logger.debug("changed service");

@@ -207,3 +207,3 @@ }

newArgs.forEach((arg) => {
if ((0, guards_js_1.has)(arg, symbols_js_1.proxyKey)) {
if ((0, pbj_guards_1.has)(arg, symbols_js_1.proxyKey)) {
this.addDependency(arg[symbols_js_1.proxyKey]);

@@ -215,3 +215,3 @@ }

/**
* Set the args to be used with the service. These can be other pbjs, or any other value.
* Set the args to be used with the service. These can be other pbinj's, or any other value.
* @param args

@@ -237,3 +237,3 @@ * @returns

* You can turn off response caching by setting this to false.
* This is useful for things taht can not be cached. Any pbj depending on a non-cacheable,
* This is useful for things that can not be cached. Any pbj depending on a non-cacheable,
* will be not cached.

@@ -240,0 +240,0 @@ *

@@ -9,3 +9,3 @@ "use strict";

exports.isInherited = isInherited;
const guards_js_1 = require("./guards.js");
const pbj_guards_1 = require("@pbinj/pbj-guards");
const symbols_js_1 = require("./symbols.js");

@@ -20,3 +20,3 @@ const toPath = (path) => path.split(/\.|\[(.+?)\]/g).filter(Boolean);

function keyOf(key) {
return (0, guards_js_1.hasA)(key, symbols_js_1.serviceSymbol, guards_js_1.isSymbol)
return (0, pbj_guards_1.hasA)(key, symbols_js_1.serviceSymbol, pbj_guards_1.isSymbol)
? key[symbols_js_1.serviceSymbol]

@@ -33,3 +33,3 @@ : key;

/**
* Concats a bunch of iterables, skipping nulls and undefined.
* Concat a bunch of iterables, skipping nulls and undefined.
* @param it

@@ -36,0 +36,0 @@ */

@@ -1,10 +0,1 @@

var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
import { describe, it, expect } from "vitest";

@@ -15,3 +6,3 @@ import { createNewContext, pbjKey } from "../index.js";

describe("resolveAsync", () => {
it("should resolve async dependencies", () => __awaiter(void 0, void 0, void 0, function* () {
it("should resolve async dependencies", async () => {
const ctx = createNewContext();

@@ -21,6 +12,6 @@ const asyncKey = pbjKey("async-value");

// Register an async service
ctx.register(asyncKey, () => __awaiter(void 0, void 0, void 0, function* () {
yield wait(10);
ctx.register(asyncKey, async () => {
await wait(10);
return "async result";
}));
});
// Register a dependent service

@@ -31,6 +22,6 @@ ctx.register(dependentKey, (asyncValue = ctx.pbj(asyncKey)) => {

// Test async resolution
const result = yield ctx.resolveAsync(dependentKey);
const result = await ctx.resolveAsync(dependentKey);
expect(result).toBe("dependent: async result");
}));
it("should handle multiple async dependencies", () => __awaiter(void 0, void 0, void 0, function* () {
});
it("should handle multiple async dependencies", async () => {
const ctx = createNewContext();

@@ -40,17 +31,17 @@ const async1 = pbjKey("async1");

const sumKey = pbjKey("sum");
ctx.register(async1, () => __awaiter(void 0, void 0, void 0, function* () {
yield new Promise((resolve) => setTimeout(resolve, 10));
ctx.register(async1, async () => {
await new Promise((resolve) => setTimeout(resolve, 10));
return 1;
}));
ctx.register(async2, () => __awaiter(void 0, void 0, void 0, function* () {
yield new Promise((resolve) => setTimeout(resolve, 10));
});
ctx.register(async2, async () => {
await new Promise((resolve) => setTimeout(resolve, 10));
return 2;
}));
});
ctx.register(sumKey, (a = ctx.pbj(async1), b = ctx.pbj(async2)) => {
return a + b;
});
const result = yield ctx.resolveAsync(sumKey);
const result = await ctx.resolveAsync(sumKey);
expect(result).toBe(3);
}));
it("should throw non-async errors", () => __awaiter(void 0, void 0, void 0, function* () {
});
it("should throw non-async errors", async () => {
const ctx = createNewContext();

@@ -61,4 +52,4 @@ const errorKey = pbjKey("error");

});
yield expect(ctx.resolveAsync(errorKey)).rejects.toThrow("test error");
}));
await expect(ctx.resolveAsync(errorKey)).rejects.toThrow("test error");
});
it("should throw an error when async is not enabled", () => {

@@ -69,6 +60,6 @@ const ctx = createNewContext();

// Register an async service
ctx.register(asyncKey, () => __awaiter(void 0, void 0, void 0, function* () {
yield wait(10);
ctx.register(asyncKey, async () => {
await wait(10);
return "async result";
}));
});
// Register a dependent service

@@ -75,0 +66,0 @@ ctx.register(dependentKey, (asyncValue = ctx.pbj(asyncKey)) => {

@@ -1,10 +0,1 @@

var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
import { it, describe, expect } from "vitest";

@@ -14,3 +5,3 @@ import { pbjKey, createNewContext } from "../index.js";

describe("onServiceAdded", () => {
it("should notify when services are added", () => __awaiter(void 0, void 0, void 0, function* () {
it("should notify when services are added", async () => {
const events = [];

@@ -24,6 +15,6 @@ const ctx = createNewContext();

ctx.register(TestService);
yield wait();
await wait();
expect(events).toEqual(["added: TestService"]);
}));
it("should notify when services change", () => __awaiter(void 0, void 0, void 0, function* () {
});
it("should notify when services change", async () => {
const events = [];

@@ -39,6 +30,6 @@ const ctx = createNewContext();

ctx.register(serviceKey, "updated");
yield wait();
await wait();
expect(events).toEqual(["changed: intital", "changed: test"]);
}));
it("should notify for tagged services", () => __awaiter(void 0, void 0, void 0, function* () {
});
it("should notify for tagged services", async () => {
const events = [];

@@ -60,6 +51,6 @@ const ctx = createNewContext();

ctx.register(PluginB).withTags(pluginKey);
yield wait();
await wait();
expect(events).toEqual(["plugin: PluginA", "plugin: PluginB"]);
}));
it("should allow unsubscribing", () => __awaiter(void 0, void 0, void 0, function* () {
});
it("should allow unsubscribing", async () => {
const events = [];

@@ -78,6 +69,6 @@ const ctx = createNewContext();

ctx.register(ServiceB);
yield wait();
await wait();
expect(events).toEqual(["ServiceA"]);
}));
it("should notify immediately for existing services", () => __awaiter(void 0, void 0, void 0, function* () {
});
it("should notify immediately for existing services", async () => {
const ctx = createNewContext();

@@ -91,6 +82,6 @@ const events = [];

});
yield wait();
await wait();
expect(events).toEqual(["existing: ExistingService"]);
}));
it("should handle multiple listeners", () => __awaiter(void 0, void 0, void 0, function* () {
});
it("should handle multiple listeners", async () => {
const ctx = createNewContext();

@@ -108,6 +99,6 @@ const events1 = [];

ctx.register(TestService);
yield wait();
await wait();
expect(events1).toEqual(["TestService"]);
expect(events2).toEqual(["TestService"]);
}));
});
});

@@ -1,10 +0,1 @@

var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var _a;

@@ -74,3 +65,3 @@ import { it, describe, expect } from "vitest";

});
it("should in inject the things", () => __awaiter(void 0, void 0, void 0, function* () {
it("should in inject the things", async () => {
ctx.register(authServiceSymbol, AuthService);

@@ -82,3 +73,3 @@ ctx.register(connectionPBinJKey, "hello");

expect(result.sendEmail("to", "what", "go")).toBeInstanceOf(Promise);
}));
});
it("should cache things", () => {

@@ -85,0 +76,0 @@ let i = 0;

@@ -1,10 +0,1 @@

var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
import { pbj } from "../../context.js";

@@ -17,10 +8,8 @@ import { DBService } from "./db.js";

}
isAuthenticated() {
return __awaiter(this, void 0, void 0, function* () {
this.dbService.connection();
console.log("authenticated");
return true;
});
async isAuthenticated() {
this.dbService.connection();
console.log("authenticated");
return true;
}
}
AuthService.service = authServiceSymbol;

@@ -1,10 +0,1 @@

var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var _a;

@@ -20,12 +11,10 @@ import { authServiceSymbol } from "./auth.js";

}
sendEmail(to, subject, body) {
return __awaiter(this, void 0, void 0, function* () {
if (yield this.authService.isAuthenticated()) {
console.log("authenticated");
}
if (this.dbService.connection()) {
console.log("connected");
}
console.log(`Email sent to ${to} with subject "${subject}" and body "${body}"`);
});
async sendEmail(to, subject, body) {
if (await this.authService.isAuthenticated()) {
console.log("authenticated");
}
if (this.dbService.connection()) {
console.log("connected");
}
console.log(`Email sent to ${to} with subject "${subject}" and body "${body}"`);
}

@@ -32,0 +21,0 @@ }

@@ -1,10 +0,1 @@

var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
import { describe, it, expect } from "vitest";

@@ -16,3 +7,3 @@ import { context, pbj, pbjKey } from "../index.js";

describe("scope", () => {
it("should maintain separate values across async operations", () => __awaiter(void 0, void 0, void 0, function* () {
it("should maintain separate values across async operations", async () => {
const scopedKey = pbjKey("async-scoped-value");

@@ -29,8 +20,8 @@ class ScopedValue {

// Create a new scope for each iteration so we can make sure scopes don't leak across async operations.
const handle = scopeHandler(() => __awaiter(void 0, void 0, void 0, function* () {
const handle = scopeHandler(async () => {
expect(sv.value.toString()).toBe(v);
//I want the promises to step on each other, to make sure its safe.
yield wait(5 * (MAX_ITER - i));
await wait(5 * (MAX_ITER - i));
expect(sv.value.toString()).toBe(v);
}), v);
}, v);
// Verify that the handler returns a promise

@@ -41,6 +32,6 @@ expect(handle).toBeInstanceOf(Promise);

}
expect((yield Promise.all(all)).length).toBe(MAX_ITER);
expect((await Promise.all(all)).length).toBe(MAX_ITER);
// Verify that accessing outside of any scope throws an error
expect(() => context.resolve(scopedKey)).toThrow();
}));
});
});

@@ -47,0 +38,0 @@ function* range(start, end, prefix = "") {

@@ -6,4 +6,4 @@ import { type Registry } from "./registry.js";

export interface Context<TRegistry extends RegistryType = Registry> {
register<TKey extends PBinJKey<TRegistry>>(tkey: TKey, ...args: ServiceArgs<TKey, TRegistry> | []): ServiceDescriptor<TRegistry, ValueOf<TRegistry, TKey>>;
resolve<TKey extends PBinJKey<TRegistry>>(tkey: TKey, ...args: ServiceArgs<TKey, TRegistry> | []): ValueOf<TRegistry, TKey>;
register<TKey extends PBinJKey<TRegistry>>(typeKey: TKey, ...args: ServiceArgs<TKey, TRegistry> | []): ServiceDescriptor<TRegistry, ValueOf<TRegistry, TKey>>;
resolve<TKey extends PBinJKey<TRegistry>>(typeKey: TKey, ...args: ServiceArgs<TKey, TRegistry> | []): ValueOf<TRegistry, TKey>;
newContext<TTRegistry extends TRegistry = TRegistry>(): Context<TTRegistry>;

@@ -15,3 +15,3 @@ pbj<T extends PBinJKey<TRegistry>>(service: T): ValueOf<TRegistry, T>;

onServiceAdded(fn: ServiceDescriptorListener, noInitial?: boolean): () => void;
resolveAsync<T extends PBinJKey<TRegistry>>(tkey: T, ...args: ServiceArgs<T, TRegistry> | []): Promise<ValueOf<TRegistry, T>>;
resolveAsync<T extends PBinJKey<TRegistry>>(typeKey: T, ...args: ServiceArgs<T, TRegistry> | []): Promise<ValueOf<TRegistry, T>>;
}

@@ -18,0 +18,0 @@ export declare class Context<TRegistry extends RegistryType = Registry> implements Context<TRegistry> {

@@ -1,12 +0,2 @@

var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var _a;
import { isConstructor, isFn, isSymbol } from "./guards.js";
import { isConstructor, isFn, isSymbol } from "@pbinj/pbj-guards";
import { PBinJError } from "./errors.js";

@@ -26,5 +16,5 @@ import { ServiceDescriptor, } from "./ServiceDescriptor.js";

}
onServiceAdded(fn, intitialize = true) {
onServiceAdded(fn, initialize = true) {
this.logger.info("onServiceAdded: listener added");
if (intitialize) {
if (initialize) {
for (const service of this.map.values()) {

@@ -42,4 +32,3 @@ for (const fn of this.listeners) {

pbj(service) {
var _a;
return ((_a = this.get(keyOf(service))) !== null && _a !== void 0 ? _a : this.register(service))
return (this.get(keyOf(service)) ?? this.register(service))
.proxy;

@@ -62,3 +51,2 @@ }

_visit(service, fn, seen = new Set()) {
var _a;
if (seen.size === seen.add(service).size) {

@@ -69,3 +57,3 @@ return;

if (ctx) {
if ((_a = ctx.dependencies) === null || _a === void 0 ? void 0 : _a.size) {
if (ctx.dependencies?.size) {
for (const dep of ctx.dependencies) {

@@ -79,8 +67,6 @@ this._visit(dep, fn, seen);

get(key) {
var _a, _b;
return (_a = this.map.get(key)) !== null && _a !== void 0 ? _a : (_b = this.parent) === null || _b === void 0 ? void 0 : _b.get(key);
return this.map.get(key) ?? this.parent?.get(key);
}
has(key) {
var _a, _b, _c;
return (_c = (_a = this.map.has(key)) !== null && _a !== void 0 ? _a : (_b = this.parent) === null || _b === void 0 ? void 0 : _b.has(key)) !== null && _c !== void 0 ? _c : false;
return this.map.has(key) ?? this.parent?.has(key) ?? false;
}

@@ -94,3 +80,3 @@ set(key, value) {

}
ctx = ctx !== null && ctx !== void 0 ? ctx : this.map.get(key);
ctx = ctx ?? this.map.get(key);
if (!ctx) {

@@ -118,3 +104,3 @@ //I don't think this should happen, but what do I know.

if (inst) {
if (origArgs === null || origArgs === void 0 ? void 0 : origArgs.length) {
if (origArgs?.length) {
this.logger.info("modifying registered service {key}", {

@@ -149,4 +135,4 @@ key: asString(serviceKey),

}
resolve(tkey, ...args) {
return this.register(tkey, ...args).invoke();
resolve(typeKey, ...args) {
return this.register(typeKey, ...args).invoke();
}

@@ -203,23 +189,21 @@ newContext() {

}
resolveAsync(key) {
return __awaiter(this, void 0, void 0, function* () {
try {
return this.resolve(key);
}
catch (e) {
if (isAsyncError(e)) {
this.logger.debug("waiting for promise[{waitKey}] for {key}", {
key: asString(key),
waitKey: asString(e.key),
});
yield e.promise;
return this.resolveAsync(key);
}
this.logger.error("error resolving async {key} {error}", {
async resolveAsync(key) {
try {
return this.resolve(key);
}
catch (e) {
if (isAsyncError(e)) {
this.logger.debug("waiting for promise[{waitKey}] for {key}", {
key: asString(key),
error: e,
waitKey: asString(e.key),
});
throw e;
await e.promise;
return this.resolveAsync(key);
}
});
this.logger.error("error resolving async {key} {error}", {
key: asString(key),
error: e,
});
throw e;
}
}

@@ -231,3 +215,3 @@ }

//Make this work when pbj is imported from multiple locations.
export const context = ((_a = globalThis["__pbj_context"]) !== null && _a !== void 0 ? _a : (globalThis["__pbj_context"] = createNewContext()));
export const context = (globalThis["__pbj_context"] ?? (globalThis["__pbj_context"] = createNewContext()));
export const pbj = context.pbj.bind(context);
var _a;
import { has } from "./guards.js";
import { has } from "@pbinj/pbj-guards";
import { asString } from "./pbjKey.js";

@@ -4,0 +4,0 @@ const symbol = Symbol("@pbj/ServiceDescriptorProxy");

@@ -1,19 +0,2 @@

import { serviceSymbol, proxyKey } from "./symbols.js";
import type { Constructor, Fn, Primitive, PrimitiveType } from "./types.js";
export declare function isSymbol(x: unknown): x is symbol;
export declare function isFn(x: unknown): x is Fn;
export declare function isService(x: unknown): x is {
[serviceSymbol]: symbol;
};
export declare function isConstructor(x: Constructor | Fn): x is Constructor;
export declare function isObjectish(x: unknown): x is object;
export declare function has(x: unknown, k: PropertyKey): x is {
[k in PropertyKey]: unknown;
};
export declare function hasA<V>(x: unknown, k: PropertyKey, guard: isA<V>): x is {
[k in PropertyKey]: V;
};
export type isA<Out> = (v: unknown) => v is Out;
export declare function isPrimitive(v: unknown): v is Primitive;
export declare function isPrimitiveType(v: unknown): v is PrimitiveType;
import { proxyKey } from "./symbols.js";
export declare function isPBinJ(v: unknown): v is {

@@ -23,3 +6,2 @@ [proxyKey]: symbol;

export declare const nullableSymbol: unique symbol;
export declare function isBoolean(v: unknown): v is boolean;
export declare function isNullish(v: unknown): v is null | undefined;

@@ -1,43 +0,3 @@

import { serviceSymbol, proxyKey } from "./symbols.js";
export function isSymbol(x) {
return typeof x === "symbol";
}
export function isFn(x) {
return typeof x === "function";
}
export function isService(x) {
return hasA(x, serviceSymbol, isSymbol);
}
export function isConstructor(x) {
return !!x.prototype && !!x.prototype.constructor.name;
}
export function isObjectish(x) {
switch (typeof x) {
case "object":
case "function":
return x != null;
default:
return false;
}
}
export function has(x, k) {
return isObjectish(x) && k in x;
}
export function hasA(x, k, guard) {
return has(x, k) ? guard(x[k]) : false;
}
export function isPrimitive(v) {
return (typeof v === "string" ||
typeof v === "number" ||
typeof v === "boolean" ||
typeof v === "symbol" ||
typeof v === "bigint");
}
export function isPrimitiveType(v) {
return (v === String ||
v === Number ||
v === Boolean ||
v === Symbol ||
v === BigInt);
}
import { proxyKey } from "./symbols.js";
import { hasA, isSymbol, isBoolean } from "@pbinj/pbj-guards";
export function isPBinJ(v) {

@@ -47,10 +7,6 @@ return hasA(v, proxyKey, isSymbol);

export const nullableSymbol = Symbol("@pbj/nullable");
export function isBoolean(v) {
return typeof v === "boolean";
}
export function isNullish(v) {
var _a;
return v == null || hasA(v, nullableSymbol, isBoolean)
? ((_a = v === null || v === void 0 ? void 0 : v.nullable) !== null && _a !== void 0 ? _a : false)
? (v?.[nullableSymbol] ?? false)
: false;
}

@@ -10,8 +10,7 @@ var _a;

return fmt.replace(/{([^}]+)}/g, (match, key) => {
var _b;
const reply = get(obj, key);
if (typeof reply === "symbol" || typeof reply === "function") {
return (_b = asString(reply)) !== null && _b !== void 0 ? _b : match;
return asString(reply) ?? match;
}
return reply !== null && reply !== void 0 ? reply : match;
return reply ?? match;
});

@@ -37,3 +36,3 @@ }

createChild(name, context = {}) {
return new Logger(this.console, this.level, name, Object.assign(Object.assign({}, this.context), context), this.format, this.maxBuffer, this);
return new Logger(this.console, this.level, name, { ...this.context, ...context }, this.format, this.maxBuffer, this);
}

@@ -79,3 +78,3 @@ resizeBuffer() {

message,
context: Object.assign(Object.assign({}, this.context), context),
context: { ...this.context, ...context },
timestamp: Date.now(),

@@ -82,0 +81,0 @@ });

@@ -1,3 +0,4 @@

import type { Constructor, Fn, ServiceDescriptorI } from "./types.js";
import { type Constructor, type Fn } from "@pbinj/pbj-guards";
import type { ServiceDescriptorI } from "./types.js";
export declare function newProxy<T extends Constructor>(key: unknown, service: ServiceDescriptorI<any, any>): InstanceType<T>;
export declare const serviceDescriptor: <T extends Fn | Constructor | unknown>(v: T) => ServiceDescriptorI<any, T> | undefined;

@@ -1,2 +0,3 @@

import { has, hasA, nullableSymbol } from "./guards.js";
import { nullableSymbol } from "./guards.js";
import { has, hasA } from "@pbinj/pbj-guards";
import { proxyKey, serviceDescriptorKey, serviceSymbol } from "./symbols.js";

@@ -3,0 +4,0 @@ export function newProxy(key, service) {

@@ -1,3 +0,4 @@

import { isFn, isPBinJ, isSymbol } from "./guards.js";
import { isPBinJ } from "./guards.js";
import { proxyKey } from "./symbols.js";
import { isFn, isSymbol } from "@pbinj/pbj-guards";
const pbjKeyMap = new WeakMap();

@@ -4,0 +5,0 @@ const anonymousMap = new WeakMap();

import { AsyncLocalStorage } from "node:async_hooks";
import { has, hasA, isFn, isSymbol } from "./guards.js";
import { has, hasA, isFn, isSymbol } from "@pbinj/pbj-guards";
import { PBinJError } from "./errors.js";

@@ -17,3 +17,3 @@ import { Context } from "./context.js";

*
* @param key - pkey or registry key
* @param key - typeKey or registry key
* @returns

@@ -36,4 +36,3 @@ */

return (next, ...[service, ...args]) => {
var _a;
const map = (_a = asyncLocalStorage.getStore()) !== null && _a !== void 0 ? _a : new Map();
const map = asyncLocalStorage.getStore() ?? new Map();
if (!map.has(key)) {

@@ -46,4 +45,3 @@ map.set(key, new ServiceDescriptor(key, service, args, false, isFn(service), `async scoped pbj '${String(key)}'`));

function getServiceDescription(key) {
var _a;
const serviceDesc = (_a = asyncLocalStorage.getStore()) === null || _a === void 0 ? void 0 : _a.get(key);
const serviceDesc = asyncLocalStorage.getStore()?.get(key);
if (!serviceDesc) {

@@ -50,0 +48,0 @@ throw new PBinJError(`key ${String(key)} not found in async storage, make sure the callback has been handled.`);

@@ -44,3 +44,3 @@ import type { Registry } from "./registry.js";

/**
* Set the args to be used with the service. These can be other pbjs, or any other value.
* Set the args to be used with the service. These can be other pbinj's, or any other value.
* @param args

@@ -58,3 +58,3 @@ * @returns

* You can turn off response caching by setting this to false.
* This is useful for things taht can not be cached. Any pbj depending on a non-cacheable,
* This is useful for things that can not be cached. Any pbj depending on a non-cacheable,
* will be not cached.

@@ -148,3 +148,3 @@ *

* The interceptor function, allows you to intercept the invocation of a service. The
* invocation may be a previous intercpetor.
* invocation may be a previous interceptor.
*/

@@ -151,0 +151,0 @@ type InterceptFn<T> = (invoke: () => T) => T;

@@ -8,3 +8,3 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {

import { keyOf } from "./util.js";
import { has, isConstructor, isFn, isPrimitive } from "./guards.js";
import { has, isConstructor, isFn, isPrimitive } from "@pbinj/pbj-guards";
import { newProxy } from "./newProxy.js";

@@ -41,3 +41,2 @@ import { proxyKey, serviceSymbol } from "./symbols.js";

this.invalidate = () => {
var _b;
if (this.invoked === false) {

@@ -50,3 +49,3 @@ return;

this._instance = undefined;
(_b = this.onChange) === null || _b === void 0 ? void 0 : _b.call(this);
this.onChange?.();
};

@@ -59,5 +58,4 @@ /**

this.invoke = () => {
var _b, _c;
if ((_b = this.interceptors) === null || _b === void 0 ? void 0 : _b.length) {
const invoke = (_c = this.interceptors) === null || _c === void 0 ? void 0 : _c.reduceRight((next, interceptor) => {
if (this.interceptors?.length) {
const invoke = this.interceptors?.reduceRight((next, interceptor) => {
return () => interceptor.call(this, next);

@@ -141,4 +139,3 @@ }, this._invoke);

get name() {
var _b;
return (_b = this._name) !== null && _b !== void 0 ? _b : asString(this[serviceSymbol]);
return this._name ?? asString(this[serviceSymbol]);
}

@@ -153,6 +150,5 @@ set name(name) {

get proxy() {
var _b;
const key = keyOf(this[serviceSymbol]);
__classPrivateFieldGet(_a, _a, "f", _ServiceDescriptor_dependencies).add(key);
return ((_b = this._proxy) !== null && _b !== void 0 ? _b : (this._proxy = newProxy(key, this)));
return (this._proxy ?? (this._proxy = newProxy(key, this)));
}

@@ -213,3 +209,3 @@ set cacheable(_cacheable) {

/**
* Set the args to be used with the service. These can be other pbjs, or any other value.
* Set the args to be used with the service. These can be other pbinj's, or any other value.
* @param args

@@ -235,3 +231,3 @@ * @returns

* You can turn off response caching by setting this to false.
* This is useful for things taht can not be cached. Any pbj depending on a non-cacheable,
* This is useful for things that can not be cached. Any pbj depending on a non-cacheable,
* will be not cached.

@@ -243,3 +239,3 @@ *

withCacheable(cacheable) {
this.cacheable = cacheable !== null && cacheable !== void 0 ? cacheable : !this.cacheable;
this.cacheable = cacheable ?? !this.cacheable;
this.invalidate();

@@ -249,3 +245,3 @@ return this;

withInvokable(invokable) {
this.invokable = invokable !== null && invokable !== void 0 ? invokable : !this.invokable;
this.invokable = invokable ?? !this.invokable;
this.invalidate();

@@ -266,3 +262,3 @@ return this;

withOptional(optional) {
this.optional = optional !== null && optional !== void 0 ? optional : !this.optional;
this.optional = optional ?? !this.optional;
this.invalidate();

@@ -307,4 +303,3 @@ return this;

withInterceptors(...interceptors) {
var _b;
this.interceptors = [...((_b = this.interceptors) !== null && _b !== void 0 ? _b : []), ...interceptors];
this.interceptors = [...(this.interceptors ?? []), ...interceptors];
return this;

@@ -322,10 +317,9 @@ }

hasDependency(key) {
var _b, _c, _d, _e;
if (this._isListOf) {
if (this._cacheable && !this.invalid) {
return (_b = this._instance) === null || _b === void 0 ? void 0 : _b.map(proxyKey).includes(key);
return this._instance?.map(proxyKey).includes(key);
}
return (_c = this.invoke()) === null || _c === void 0 ? void 0 : _c.map(proxyKey).includes(key);
return this.invoke()?.map(proxyKey).includes(key);
}
return (_e = (_d = this.dependencies) === null || _d === void 0 ? void 0 : _d.has(key)) !== null && _e !== void 0 ? _e : false;
return this.dependencies?.has(key) ?? false;
}

@@ -338,5 +332,4 @@ /**

addDependency(...keys) {
var _b;
if (keys.length) {
const set = ((_b = this.dependencies) !== null && _b !== void 0 ? _b : (this.dependencies = new Set()));
const set = (this.dependencies ?? (this.dependencies = new Set()));
keys.forEach((v) => set.add(v));

@@ -354,3 +347,2 @@ }

toJSON() {
var _b, _c;
return {

@@ -368,4 +360,4 @@ name: this.name,

error: this.error,
dependencies: Array.from((_b = this.dependencies) !== null && _b !== void 0 ? _b : [], asString),
args: (_c = this.args) === null || _c === void 0 ? void 0 : _c.map(asString),
dependencies: Array.from(this.dependencies ?? [], asString),
args: this.args?.map(asString),
};

@@ -372,0 +364,0 @@ }

@@ -7,3 +7,3 @@ import type { CKey, PBinJKey, Service } from "./types.js";

/**
* Concats a bunch of iterables, skipping nulls and undefined.
* Concat a bunch of iterables, skipping nulls and undefined.
* @param it

@@ -10,0 +10,0 @@ */

@@ -1,2 +0,2 @@

import { hasA, isSymbol } from "./guards.js";
import { hasA, isSymbol } from "@pbinj/pbj-guards";
import { serviceSymbol } from "./symbols.js";

@@ -6,5 +6,5 @@ const toPath = (path) => path.split(/\.|\[(.+?)\]/g).filter(Boolean);

const value = toPath(key).reduce((acc, part) => {
return acc === null || acc === void 0 ? void 0 : acc[part];
return acc?.[part];
}, obj);
return value !== null && value !== void 0 ? value : defaultValue;
return value ?? defaultValue;
}

@@ -24,3 +24,3 @@ export function keyOf(key) {

/**
* Concats a bunch of iterables, skipping nulls and undefined.
* Concat a bunch of iterables, skipping nulls and undefined.
* @param it

@@ -27,0 +27,0 @@ */

{
"name": "@pbinj/pbj",
"version": "2.0.0",
"version": "3.0.0",
"license": "MIT",

@@ -21,6 +21,2 @@ "description": "A lightweight Dependency Injection (DI) framework for Node.js, based on proxies.",

},
"./guards": {
"import": "./dist/esm/guards.js",
"require": "./dist/cjs/guards.js"
},
"./logger": {

@@ -64,5 +60,10 @@ "import": "./dist/esm/logger.js",

},
"dependencies": {
"@pbinj/pbj-guards": "3.0.0"
},
"scripts": {
"test": "vitest run",
"build": "tsc && tsc -p tsconfig.cjs.json",
"build:esm": "tsc",
"build:cjs": "tsc -p tsconfig.cjs.json",
"build": "${npm_execpath} run build:esm && ${npm_execpath} run build:cjs",
"watch": "tsc -w",

@@ -69,0 +70,0 @@ "clean": "rm -rf dist",