Skip to content

Commit

Permalink
fix(cordis): support has handler, support frozen objects
Browse files Browse the repository at this point in the history
  • Loading branch information
shigma committed Aug 15, 2024
1 parent 50d097b commit aa4f973
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 5 deletions.
20 changes: 15 additions & 5 deletions packages/core/src/reflect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,14 +43,14 @@ class ReflectService {
}

static handler: ProxyHandler<Context> = {
get(target, prop, ctx: Context) {
get: (target, prop, ctx: Context) => {
if (typeof prop !== 'string') return Reflect.get(target, prop, ctx)

if (Reflect.has(target, prop)) {
return getTraceable(ctx, Reflect.get(target, prop, ctx), true)
}

const [name, internal] = ReflectService.resolveInject(ctx, prop)
const [name, internal] = ReflectService.resolveInject(target, prop)
// trace caller
const error = new Error(`property ${name} is not registered, declare it as \`inject\` to suppress this warning`)
const lines = error.stack!.split('\n')
Expand All @@ -67,10 +67,10 @@ class ReflectService {
}
},

set(target, prop, value, ctx: Context) {
set: (target, prop, value, ctx: Context) => {
if (typeof prop !== 'string') return Reflect.set(target, prop, value, ctx)

const [name, internal] = ReflectService.resolveInject(ctx, prop)
const [name, internal] = ReflectService.resolveInject(target, prop)
if (!internal) {
// TODO warning
return Reflect.set(target, name, value, ctx)
Expand All @@ -84,6 +84,13 @@ class ReflectService {
return true
}
},

has: (target, prop) => {
if (typeof prop !== 'string') return Reflect.has(target, prop)
if (Reflect.has(target, prop)) return true
const [, internal] = ReflectService.resolveInject(target, prop)
return !!internal
},
}

constructor(public ctx: Context) {
Expand Down Expand Up @@ -136,7 +143,10 @@ class ReflectService {
ctx.emit(self, 'internal/before-service', name, value)
ctx.root[key] = value
if (isObject(value)) {
defineProperty(value, symbols.source, ctx)
try {
// Frozen objects cannot be modified
defineProperty(value, symbols.source, ctx)
} catch {}
}
ctx.emit(self, 'internal/service', name, oldValue)
return dispose
Expand Down
1 change: 1 addition & 0 deletions packages/loader/src/loader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,7 @@ export abstract class Loader<C extends Context = Context> extends ImportTree<C>

async start() {
await this.init(process.cwd(), this.config)
this.ctx.set('env', process.env)
await super.start()
}

Expand Down

0 comments on commit aa4f973

Please sign in to comment.