kreftjs 0.0.0-stage → 0.0.2-beta
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +103 -2
- package/bin/add.js +1074 -0
- package/bin/artisan-more.js +994 -0
- package/bin/artisan.js +1877 -0
- package/bin/backend/app.js +161 -0
- package/bin/backend/cache.js +196 -0
- package/bin/backend/collection.js +117 -0
- package/bin/backend/command.js +45 -0
- package/bin/backend/config.js +234 -0
- package/bin/backend/error-page.js +773 -0
- package/bin/backend/events.js +49 -0
- package/bin/backend/factory.js +223 -0
- package/bin/backend/fake.js +180 -0
- package/bin/backend/form.js +102 -0
- package/bin/backend/gate.js +79 -0
- package/bin/backend/gc.js +69 -0
- package/bin/backend/html.js +322 -0
- package/bin/backend/http.js +652 -0
- package/bin/backend/index.js +452 -0
- package/bin/backend/mail.js +77 -0
- package/bin/backend/mcp.js +433 -0
- package/bin/backend/migrator.js +370 -0
- package/bin/backend/model.js +781 -0
- package/bin/backend/namespace.js +213 -0
- package/bin/backend/notifications.js +68 -0
- package/bin/backend/qr.js +164 -0
- package/bin/backend/query.js +387 -0
- package/bin/backend/queue.js +412 -0
- package/bin/backend/redis.js +479 -0
- package/bin/backend/schedule.js +112 -0
- package/bin/backend/schema.js +321 -0
- package/bin/backend/seo-pages.js +100 -0
- package/bin/backend/storage.js +153 -0
- package/bin/backend/support.js +567 -0
- package/bin/backend/typescript.js +166 -0
- package/bin/build.js +540 -0
- package/bin/db-api.js +249 -0
- package/bin/db.js +275 -0
- package/bin/deps.js +138 -0
- package/bin/electron.js +509 -0
- package/bin/env.js +97 -0
- package/bin/guard.js +80 -0
- package/bin/kreftjs-config.js +40 -0
- package/bin/kreftjs.js +1373 -0
- package/bin/lang.js +241 -0
- package/bin/layout.js +74 -0
- package/bin/no-auth.js +162 -0
- package/bin/prerender.js +258 -0
- package/bin/safe-json.js +24 -0
- package/bin/server-routes.js +154 -0
- package/bin/ssr.js +133 -0
- package/bin/terminal.js +195 -0
- package/bin/to-ts.js +36 -0
- package/bin/update.js +237 -0
- package/bin/urls-file.js +27 -0
- package/bin/vite.js +228 -0
- package/docs/Docs.kreftjs +557 -0
- package/docs/README.md +2302 -0
- package/docs/markdown.js +186 -0
- package/editors/vscode/README.md +13 -0
- package/editors/vscode/extension.js +183 -0
- package/editors/vscode/language-configuration.json +17 -0
- package/editors/vscode/package.json +57 -0
- package/editors/vscode/snippets/kreftjs.json +21 -0
- package/editors/vscode/syntaxes/kreftjs.tmLanguage.json +207 -0
- package/kreftjs.d.ts +579 -0
- package/kreftjs.js +5108 -0
- package/package.json +97 -4
- package/server.d.ts +1028 -0
- package/server.js +8 -0
- package/templates/app/README.md +127 -0
- package/templates/app/_env.example +64 -0
- package/templates/app/_gitignore +5 -0
- package/templates/app/_vscode/settings.json +9 -0
- package/templates/app/backend/app/Auth/Session.js +177 -0
- package/templates/app/backend/app/Auth/Throttle.js +29 -0
- package/templates/app/backend/app/Console/Commands/.gitkeep +0 -0
- package/templates/app/backend/app/Events/.gitkeep +0 -0
- package/templates/app/backend/app/Http/Controllers/Admin/DashboardController.js +34 -0
- package/templates/app/backend/app/Http/Controllers/Admin/UserController.js +53 -0
- package/templates/app/backend/app/Http/Controllers/Auth/ApiTokenController.js +47 -0
- package/templates/app/backend/app/Http/Controllers/Auth/AuthenticatedSessionController.js +41 -0
- package/templates/app/backend/app/Http/Controllers/Auth/ConfirmablePasswordController.js +14 -0
- package/templates/app/backend/app/Http/Controllers/Auth/EmailVerificationController.js +23 -0
- package/templates/app/backend/app/Http/Controllers/Auth/NewPasswordController.js +29 -0
- package/templates/app/backend/app/Http/Controllers/Auth/PasswordResetLinkController.js +20 -0
- package/templates/app/backend/app/Http/Controllers/Auth/RegisteredUserController.js +19 -0
- package/templates/app/backend/app/Http/Controllers/Auth/SessionController.js +36 -0
- package/templates/app/backend/app/Http/Controllers/Auth/TwoFactorChallengeController.js +41 -0
- package/templates/app/backend/app/Http/Controllers/Auth/TwoFactorController.js +63 -0
- package/templates/app/backend/app/Http/Controllers/ProfileController.js +66 -0
- package/templates/app/backend/app/Http/Kernel.js +8 -0
- package/templates/app/backend/app/Http/Middleware/Authenticate.js +84 -0
- package/templates/app/backend/app/Http/Middleware/CheckAbilities.js +17 -0
- package/templates/app/backend/app/Http/Middleware/CheckForAnyAbility.js +12 -0
- package/templates/app/backend/app/Http/Middleware/EnsureEmailIsVerified.js +11 -0
- package/templates/app/backend/app/Http/Middleware/EnsureHasRole.js +11 -0
- package/templates/app/backend/app/Http/Middleware/EnsureIsAdmin.js +11 -0
- package/templates/app/backend/app/Http/Middleware/RequirePassword.js +15 -0
- package/templates/app/backend/app/Http/Requests/Auth/LoginRequest.js +45 -0
- package/templates/app/backend/app/Http/Resources/.gitkeep +1 -0
- package/templates/app/backend/app/Jobs/.gitkeep +0 -0
- package/templates/app/backend/app/Listeners/.gitkeep +0 -0
- package/templates/app/backend/app/Mail/.gitkeep +0 -0
- package/templates/app/backend/app/Models/PersonalAccessToken.js +21 -0
- package/templates/app/backend/app/Models/User.js +64 -0
- package/templates/app/backend/app/Notifications/.gitkeep +0 -0
- package/templates/app/backend/app/Observers/.gitkeep +0 -0
- package/templates/app/backend/app/Policies/.gitkeep +0 -0
- package/templates/app/backend/app/Providers/AppServiceProvider.js +12 -0
- package/templates/app/backend/app/Rules/.gitkeep +1 -0
- package/templates/app/backend/config/app.js +16 -0
- package/templates/app/backend/config/auth.js +34 -0
- package/templates/app/backend/config/database.js +38 -0
- package/templates/app/backend/config/redis.js +28 -0
- package/templates/app/backend/config/session.js +36 -0
- package/templates/app/backend/database/migrations/0001_01_01_000000_create_users_table.js +49 -0
- package/templates/app/backend/database/migrations/0001_01_01_000001_create_cache_table.js +13 -0
- package/templates/app/backend/database/migrations/0001_01_01_000002_create_jobs_table.js +26 -0
- package/templates/app/backend/database/migrations/0001_01_01_000003_create_notifications_table.js +18 -0
- package/templates/app/backend/database/seeders/DatabaseSeeder.js +15 -0
- package/templates/app/backend/lang/ar/messages.json +10 -0
- package/templates/app/backend/lang/ar/validation.json +21 -0
- package/templates/app/backend/lang/en/messages.json +10 -0
- package/templates/app/backend/lang/en/validation.json +19 -0
- package/templates/app/backend/routes/api.js +25 -0
- package/templates/app/backend/routes/auth.js +52 -0
- package/templates/app/backend/routes/console.js +15 -0
- package/templates/app/frontend/App.kreftjs +4 -0
- package/templates/app/frontend/components/Field.kreftjs +19 -0
- package/templates/app/frontend/components/StatCard.kreftjs +47 -0
- package/templates/app/frontend/components/profile/ApiTokens.kreftjs +70 -0
- package/templates/app/frontend/components/profile/Sessions.kreftjs +42 -0
- package/templates/app/frontend/components/profile/TwoFactor.kreftjs +90 -0
- package/templates/app/frontend/errors/ErrorMonitor.kreftjs +264 -0
- package/templates/app/frontend/index.html +79 -0
- package/templates/app/frontend/kreftjs.d.ts +579 -0
- package/templates/app/frontend/kreftjs.js +5108 -0
- package/templates/app/frontend/layouts/app.kreftjs +718 -0
- package/templates/app/frontend/layouts/docs.kreftjs +37 -0
- package/templates/app/frontend/layouts/guest.kreftjs +18 -0
- package/templates/app/frontend/pages/Dashboard.kreftjs +273 -0
- package/templates/app/frontend/pages/ErrorMonitor.kreftjs +96 -0
- package/templates/app/frontend/pages/Home.kreftjs +617 -0
- package/templates/app/frontend/pages/Profile.kreftjs +104 -0
- package/templates/app/frontend/pages/Users.kreftjs +240 -0
- package/templates/app/frontend/pages/auth/ConfirmPassword.kreftjs +33 -0
- package/templates/app/frontend/pages/auth/ForgotPassword.kreftjs +36 -0
- package/templates/app/frontend/pages/auth/Login.kreftjs +89 -0
- package/templates/app/frontend/pages/auth/Register.kreftjs +48 -0
- package/templates/app/frontend/pages/auth/ResetPassword.kreftjs +45 -0
- package/templates/app/frontend/pages/auth/VerifyEmail.kreftjs +59 -0
- package/templates/app/frontend/routes/web.kreftjs +34 -0
- package/templates/app/frontend/tests/components/Counter.kreftjs +15 -0
- package/templates/app/frontend/tests/pages/About.kreftjs +12 -0
- package/templates/app/frontend/tests/pages/Test.kreftjs +31 -0
- package/templates/app/frontend/ui.css +517 -0
- package/templates/app/lang/ar/auth.json +6 -0
- package/templates/app/lang/ar/messages.json +6 -0
- package/templates/app/lang/ar/pagination.json +5 -0
- package/templates/app/lang/ar/passwords.json +8 -0
- package/templates/app/lang/ar/validation.json +22 -0
- package/templates/app/lang/ar.json +10 -0
- package/templates/app/lang/en/auth.json +6 -0
- package/templates/app/lang/en/messages.json +6 -0
- package/templates/app/lang/en/pagination.json +5 -0
- package/templates/app/lang/en/passwords.json +8 -0
- package/templates/app/lang/en/validation.json +22 -0
- package/templates/app/lang/en.json +10 -0
- package/templates/errors/401.kreftjs +11 -0
- package/templates/errors/402.kreftjs +11 -0
- package/templates/errors/403.kreftjs +11 -0
- package/templates/errors/404.kreftjs +11 -0
- package/templates/errors/419.kreftjs +11 -0
- package/templates/errors/429.kreftjs +11 -0
- package/templates/errors/500.kreftjs +11 -0
- package/templates/errors/503.kreftjs +11 -0
- package/templates/errors/ErrorMonitor.kreftjs +502 -0
- package/templates/errors/error.kreftjs +11 -0
- package/templates/errors/minimal.kreftjs +25 -0
- package/tools/dev-client.js +125 -0
- package/tools/devtools.js +172 -0
- package/tools/vite-plugin-kreftjs.d.ts +52 -0
- package/tools/vite-plugin-kreftjs.js +466 -0
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Events and listeners system.
|
|
3
|
+
*
|
|
4
|
+
* // app/Events/OrderShipped.js
|
|
5
|
+
* class OrderShipped { constructor(order) { this.order = order } }
|
|
6
|
+
*
|
|
7
|
+
* // app/Listeners/SendShipmentNotice.js — found by itself
|
|
8
|
+
* class SendShipmentNotice {
|
|
9
|
+
* static event = 'OrderShipped' // the event's class name (or the class, or a list)
|
|
10
|
+
* static queue = true // optional: run it later, on the queue
|
|
11
|
+
* async handle(event) { await Mail.to(event.order.email).send(new ShipmentMail(event.order)) }
|
|
12
|
+
* }
|
|
13
|
+
*
|
|
14
|
+
* await event(new OrderShipped(order)) or Event.dispatch('user.login', user)
|
|
15
|
+
* Event.listen('user.login', (user) => Log.info('login', { id: user.id }))
|
|
16
|
+
*/
|
|
17
|
+
const listeners = new Map(); // event name → [listener]
|
|
18
|
+
const nameOf = (e) => (typeof e === 'string' ? e : typeof e === 'function' ? e.name : e && e.constructor ? e.constructor.name : String(e));
|
|
19
|
+
|
|
20
|
+
const Event = {
|
|
21
|
+
listen(event, listener) {
|
|
22
|
+
for (const ev of [].concat(event)) {
|
|
23
|
+
const key = nameOf(ev);
|
|
24
|
+
if (!listeners.has(key)) listeners.set(key, []);
|
|
25
|
+
listeners.get(key).push(listener);
|
|
26
|
+
}
|
|
27
|
+
},
|
|
28
|
+
hasListeners: (event) => (listeners.get(nameOf(event)) || []).length > 0,
|
|
29
|
+
forget(event) { listeners.delete(nameOf(event)); },
|
|
30
|
+
reset() { listeners.clear(); },
|
|
31
|
+
// runs every listener (queued ones go to the queue); a listener that returns false stops the rest
|
|
32
|
+
async dispatch(event, ...payload) {
|
|
33
|
+
const list = listeners.get(nameOf(event)) || [];
|
|
34
|
+
const results = [];
|
|
35
|
+
for (const L of list) {
|
|
36
|
+
let r;
|
|
37
|
+
if (typeof L === 'function' && !/^class\s/.test(Function.prototype.toString.call(L))) r = await L(event, ...payload);
|
|
38
|
+
else if (typeof L === 'function' && L.queue) { await require('./queue.js').push('listener', L.name, { event: typeof event === 'object' ? { class: event.constructor.name, data: { ...event } } : event, payload }, { queue: typeof L.queue === 'string' ? L.queue : undefined }); continue; }
|
|
39
|
+
else { const inst = typeof L === 'function' ? new L() : L; r = await inst.handle(event, ...payload); }
|
|
40
|
+
results.push(r);
|
|
41
|
+
if (r === false) break;
|
|
42
|
+
}
|
|
43
|
+
return results;
|
|
44
|
+
},
|
|
45
|
+
listeners: () => [...listeners].map(([event, list]) => ({ event, listeners: list.map((l) => l.name || 'Closure') })),
|
|
46
|
+
};
|
|
47
|
+
const event = (e, ...payload) => Event.dispatch(e, ...payload);
|
|
48
|
+
|
|
49
|
+
module.exports = { Event, event, nameOf };
|
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Model factories: rows for tests and seeders.
|
|
3
|
+
*
|
|
4
|
+
* // database/factories/UserFactory.js
|
|
5
|
+
* const { Factory, Hash } = require('kreftjs/server')
|
|
6
|
+
* const User = require('../../app/Models/User')
|
|
7
|
+
* module.exports = Factory.define(User, (fake) => ({
|
|
8
|
+
* name: fake.name(),
|
|
9
|
+
* email: fake.unique().email(),
|
|
10
|
+
* password: Hash.make('password'),
|
|
11
|
+
* }))
|
|
12
|
+
* .state('admin', { is_admin: true }) // User.factory().admin().create()
|
|
13
|
+
*
|
|
14
|
+
* await User.factory().count(10).create()
|
|
15
|
+
* await User.factory().state({ is_admin: true }).create({ name: 'Maxamuud' })
|
|
16
|
+
* const draft = await Post.factory().make() // not saved
|
|
17
|
+
* await Post.factory().count(3).for(user).create() // user_id filled in
|
|
18
|
+
* await User.factory().has(Post.factory().count(3), 'posts').create()
|
|
19
|
+
*/
|
|
20
|
+
const { fake } = require('./fake.js');
|
|
21
|
+
const { Collection } = require('./collection.js');
|
|
22
|
+
|
|
23
|
+
const definitions = new Map(); // Model → { define, states }
|
|
24
|
+
|
|
25
|
+
class Factory {
|
|
26
|
+
static define(Model, define) {
|
|
27
|
+
if (Model && Model.default) Model = Model.default;
|
|
28
|
+
const def = { Model, define, states: {} };
|
|
29
|
+
definitions.set(Model, def);
|
|
30
|
+
|
|
31
|
+
function factoryFn(countOrAttrs) {
|
|
32
|
+
const inst = Factory.for(Model);
|
|
33
|
+
if (typeof countOrAttrs === 'number') {
|
|
34
|
+
return inst.count(countOrAttrs);
|
|
35
|
+
}
|
|
36
|
+
if (countOrAttrs && typeof countOrAttrs === 'object') {
|
|
37
|
+
return inst.state(countOrAttrs);
|
|
38
|
+
}
|
|
39
|
+
return inst;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
Object.setPrototypeOf(factoryFn.prototype, Factory.prototype);
|
|
43
|
+
|
|
44
|
+
factoryFn.def = def;
|
|
45
|
+
factoryFn.Model = Model;
|
|
46
|
+
factoryFn.default = factoryFn;
|
|
47
|
+
if (Model && Model.name) {
|
|
48
|
+
factoryFn[Model.name + 'Factory'] = factoryFn;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
factoryFn.state = function(nameOrValues, values) {
|
|
52
|
+
if (typeof nameOrValues === 'string' && values !== undefined) {
|
|
53
|
+
def.states[nameOrValues] = values;
|
|
54
|
+
return proxy;
|
|
55
|
+
}
|
|
56
|
+
const inst = Factory.for(Model);
|
|
57
|
+
if (typeof nameOrValues === 'string' && def.states[nameOrValues]) {
|
|
58
|
+
return inst.state(def.states[nameOrValues]);
|
|
59
|
+
}
|
|
60
|
+
return inst.state(nameOrValues);
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
factoryFn.count = function(n) {
|
|
64
|
+
return Factory.for(Model).count(n);
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
factoryFn.create = function(extra) {
|
|
68
|
+
return Factory.for(Model).create(extra);
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
factoryFn.make = function(extra) {
|
|
72
|
+
return Factory.for(Model).make(extra);
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
factoryFn.raw = function(extra) {
|
|
76
|
+
return Factory.for(Model).raw(extra);
|
|
77
|
+
};
|
|
78
|
+
|
|
79
|
+
factoryFn.sequence = function(...vals) {
|
|
80
|
+
return Factory.for(Model).sequence(...vals);
|
|
81
|
+
};
|
|
82
|
+
|
|
83
|
+
factoryFn.for = function(parent, key) {
|
|
84
|
+
return Factory.for(Model).for(parent, key);
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
factoryFn.has = function(child, rel) {
|
|
88
|
+
return Factory.for(Model).has(child, rel);
|
|
89
|
+
};
|
|
90
|
+
|
|
91
|
+
factoryFn.clone = function() {
|
|
92
|
+
return Factory.for(Model).clone();
|
|
93
|
+
};
|
|
94
|
+
|
|
95
|
+
const proxy = new Proxy(factoryFn, {
|
|
96
|
+
get(target, prop, receiver) {
|
|
97
|
+
if (prop in target) return target[prop];
|
|
98
|
+
if (typeof prop === 'string') {
|
|
99
|
+
if (prop in def.states) {
|
|
100
|
+
return (...args) => Factory.for(Model)[prop](...args);
|
|
101
|
+
}
|
|
102
|
+
if (typeof Factory.prototype[prop] === 'function') {
|
|
103
|
+
return (...args) => Factory.for(Model)[prop](...args);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
return target[prop];
|
|
107
|
+
},
|
|
108
|
+
apply(target, thisArg, argList) {
|
|
109
|
+
return target(...argList);
|
|
110
|
+
},
|
|
111
|
+
construct(target, argList, newTarget) {
|
|
112
|
+
return target(...argList);
|
|
113
|
+
}
|
|
114
|
+
});
|
|
115
|
+
|
|
116
|
+
return proxy;
|
|
117
|
+
}
|
|
118
|
+
static for(Model) {
|
|
119
|
+
if (Model && Model.default) Model = Model.default;
|
|
120
|
+
let def = definitions.get(Model);
|
|
121
|
+
if (!def && Model && Model.name) {
|
|
122
|
+
for (const [m, d] of definitions.entries()) {
|
|
123
|
+
if (m.name === Model.name || (d.Model && d.Model.name === Model.name)) {
|
|
124
|
+
def = d;
|
|
125
|
+
definitions.set(Model, def);
|
|
126
|
+
break;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
if (!def && Model && Model.name) {
|
|
131
|
+
const { factoryFile } = require('./model.js');
|
|
132
|
+
const file = factoryFile(Model.name);
|
|
133
|
+
if (file) {
|
|
134
|
+
require(file);
|
|
135
|
+
def = definitions.get(Model);
|
|
136
|
+
if (!def) {
|
|
137
|
+
for (const [m, d] of definitions.entries()) {
|
|
138
|
+
if (m.name === Model.name || (d.Model && d.Model.name === Model.name)) {
|
|
139
|
+
def = d;
|
|
140
|
+
definitions.set(Model, def);
|
|
141
|
+
break;
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
if (!def) throw new Error(`No factory for ${Model && Model.name ? Model.name : 'Model'}. Make one: kreftjs make:factory ${(Model && Model.name) || 'Model'}Factory`);
|
|
148
|
+
return new Factory(def);
|
|
149
|
+
}
|
|
150
|
+
constructor(def) {
|
|
151
|
+
this.def = def;
|
|
152
|
+
this.n = null;
|
|
153
|
+
this.states = [];
|
|
154
|
+
this.parents = [];
|
|
155
|
+
this.children = [];
|
|
156
|
+
this.seq = null;
|
|
157
|
+
// named states become methods: User.factory().admin()
|
|
158
|
+
for (const name of Object.keys(def.states)) if (!(name in this)) this[name] = () => this.state(def.states[name]);
|
|
159
|
+
}
|
|
160
|
+
clone() { const f = new Factory(this.def); Object.assign(f, { n: this.n, states: [...this.states], parents: [...this.parents], children: [...this.children], seq: this.seq }); return f; }
|
|
161
|
+
count(n) { const f = this.clone(); f.n = n; return f; }
|
|
162
|
+
state(values) {
|
|
163
|
+
const f = this.clone();
|
|
164
|
+
if (typeof values === 'string' && this.def && this.def.states && this.def.states[values]) {
|
|
165
|
+
values = this.def.states[values];
|
|
166
|
+
}
|
|
167
|
+
f.states.push(values);
|
|
168
|
+
return f;
|
|
169
|
+
}
|
|
170
|
+
// sequence({ role: 'a' }, { role: 'b' }): row 1 gets the first, row 2 the second, then again
|
|
171
|
+
sequence(...values) { const f = this.clone(); f.seq = values; return f; }
|
|
172
|
+
// for(user) or for(user, 'author_id'): belongs to that model
|
|
173
|
+
for(parent, key) { const f = this.clone(); f.parents.push({ parent, key }); return f; }
|
|
174
|
+
// has(Post.factory().count(3), 'posts'): made after each row, through the relation
|
|
175
|
+
has(child, relationName) { const f = this.clone(); f.children.push({ child, relationName }); return f; }
|
|
176
|
+
|
|
177
|
+
attributes(i, extra) {
|
|
178
|
+
let attrs = { ...this.def.define(fake, i) };
|
|
179
|
+
for (const [k, v] of Object.entries(attrs)) {
|
|
180
|
+
if (typeof v === 'function') attrs[k] = v(attrs, fake, i);
|
|
181
|
+
}
|
|
182
|
+
for (const s of this.states) attrs = { ...attrs, ...(typeof s === 'function' ? s(attrs, fake) : s) };
|
|
183
|
+
if (this.seq) { const s = this.seq[i % this.seq.length]; attrs = { ...attrs, ...(typeof s === 'function' ? s(i) : s) }; }
|
|
184
|
+
for (const { parent, key } of this.parents) {
|
|
185
|
+
const k = key || require('./model.js').snake(parent.constructor.name) + '_id';
|
|
186
|
+
attrs[k] = parent[parent.constructor.primaryKey];
|
|
187
|
+
}
|
|
188
|
+
return { ...attrs, ...(extra || {}) };
|
|
189
|
+
}
|
|
190
|
+
// raw(): just the values
|
|
191
|
+
raw(extra) { return this.n == null ? this.attributes(0, extra) : Array.from({ length: this.n }, (_, i) => this.attributes(i, extra)); }
|
|
192
|
+
// make(): models, not saved
|
|
193
|
+
async make(extra) {
|
|
194
|
+
const one = (i) => new this.def.Model().forceFill(this.attributes(i, extra));
|
|
195
|
+
return this.n == null ? one(0) : Collection.from(Array.from({ length: this.n }, (_, i) => one(i)));
|
|
196
|
+
}
|
|
197
|
+
// create(): saved (hooks run); fields that aren't fillable are still set
|
|
198
|
+
async create(extra) {
|
|
199
|
+
const run = async () => {
|
|
200
|
+
const made = new Collection();
|
|
201
|
+
for (let i = 0; i < (this.n == null ? 1 : this.n); i++) {
|
|
202
|
+
const m = new this.def.Model().forceFill(this.attributes(i, extra));
|
|
203
|
+
await m.save();
|
|
204
|
+
for (const { child, relationName } of this.children) {
|
|
205
|
+
const name = relationName || require('./model.js').singular(child.def.Model.table) + 's';
|
|
206
|
+
const rel = m[name]();
|
|
207
|
+
const key = rel.__rel.foreignKey;
|
|
208
|
+
await child.state({ [key]: m[rel.__rel.localKey] }).create();
|
|
209
|
+
}
|
|
210
|
+
made.push(m);
|
|
211
|
+
}
|
|
212
|
+
return this.n == null ? made[0] : made;
|
|
213
|
+
};
|
|
214
|
+
const p = run();
|
|
215
|
+
Factory.pendingCreations.add(p);
|
|
216
|
+
p.finally(() => Factory.pendingCreations.delete(p));
|
|
217
|
+
return p;
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
Factory.pendingCreations = new Set();
|
|
222
|
+
|
|
223
|
+
module.exports = { Factory };
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Fake data for factories and seeders, like Faker (no package needed).
|
|
3
|
+
*
|
|
4
|
+
* fake.name() fake.email() fake.sentence() fake.paragraph() fake.number(1, 100)
|
|
5
|
+
* fake.boolean() fake.date() fake.uuid() fake.phone() fake.city() fake.pick(['a', 'b'])
|
|
6
|
+
* fake.unique().email() — never the same value twice (until fake.unique().reset())
|
|
7
|
+
*/
|
|
8
|
+
const crypto = require('crypto');
|
|
9
|
+
|
|
10
|
+
const FIRST = ['Maxamuud', 'Amina', 'Cabdi', 'Hodan', 'Faadumo', 'Yuusuf', 'Sahra', 'Ahmed', 'Layla', 'Omar', 'Noor', 'Ali', 'Ifrah', 'Khalid', 'Maryam', 'Hassan',
|
|
11
|
+
'Sara', 'Daniel', 'Emma', 'Lucas', 'Mia', 'Noah', 'Olivia', 'Liam', 'Ava', 'Ethan', 'Zara', 'Ibrahim', 'Fatima', 'Yasmin', 'Adam', 'Hana'];
|
|
12
|
+
const LAST = ['Xussen', 'Cali', 'Yuusuf', 'Warsame', 'Jaamac', 'Faarax', 'Maxamed', 'Nuur', 'Aadan', 'Saleebaan', 'Ismaaciil', 'Osman',
|
|
13
|
+
'Smith', 'Johnson', 'Garcia', 'Khan', 'Haddad', 'Mansour', 'Rahman', 'Novak', 'Silva', 'Kim', 'Ali', 'Farah'];
|
|
14
|
+
const WORDS = ('lorem ipsum dolor sit amet consectetur adipiscing elit sed do eiusmod tempor incididunt ut labore et dolore magna aliqua ' +
|
|
15
|
+
'enim ad minim veniam quis nostrud exercitation ullamco laboris nisi aliquip ex ea commodo consequat duis aute irure in reprehenderit ' +
|
|
16
|
+
'voluptate velit esse cillum fugiat nulla pariatur excepteur sint occaecat cupidatat non proident sunt culpa qui officia deserunt mollit anim id est laborum').split(' ');
|
|
17
|
+
const CITIES = ['Mogadishu', 'Hargeisa', 'Berbera', 'Kismayo', 'Garowe', 'Bosaso', 'Nairobi', 'Dubai', 'Cairo', 'Istanbul', 'London', 'Toronto', 'Doha', 'Riyadh'];
|
|
18
|
+
const COUNTRIES = ['Somalia', 'Kenya', 'Ethiopia', 'Djibouti', 'United Arab Emirates', 'Egypt', 'Turkey', 'United Kingdom', 'Canada', 'Qatar', 'Saudi Arabia'];
|
|
19
|
+
const COMPANIES = ['Hormuud', 'Dahabshiil', 'Telesom', 'Golis', 'Premier', 'Salaam', 'Amal', 'Juba', 'Horizon', 'Nile', 'Atlas', 'Sahan'];
|
|
20
|
+
const SUFFIX = ['Group', 'Ltd', 'Solutions', 'Trading', 'Services', 'Tech', 'Holdings'];
|
|
21
|
+
const DOMAINS = ['example.com', 'example.org', 'example.net'];
|
|
22
|
+
|
|
23
|
+
const CATEGORIES = [
|
|
24
|
+
'Electronics', 'Computers & Accessories', 'Smartphones & Tablets', 'Home & Kitchen',
|
|
25
|
+
'Fashion & Apparel', 'Health & Personal Care', 'Beauty & Cosmetics', 'Sports & Fitness',
|
|
26
|
+
'Outdoor & Recreation', 'Books & Literature', 'Automotive', 'Toys & Games',
|
|
27
|
+
'Groceries & Food', 'Software & Apps', 'Furniture & Interior', 'Jewelry & Watches',
|
|
28
|
+
'Garden & Tools', 'Music & Audio', 'Video Games & Consoles', 'Office Supplies',
|
|
29
|
+
'Pet Supplies', 'Travel & Luggage', 'Baby & Kids', 'Arts & Crafts', 'Industrial & Scientific',
|
|
30
|
+
'Food & Beverages', 'Photography & Video', 'Smart Home', 'Watches & Accessories', 'Shoes & Footwear',
|
|
31
|
+
];
|
|
32
|
+
const DEPARTMENTS = [
|
|
33
|
+
'Engineering', 'Product Management', 'Design & UX', 'Marketing', 'Sales',
|
|
34
|
+
'Customer Support', 'Human Resources', 'Finance', 'Legal', 'Operations',
|
|
35
|
+
'Research & Development', 'Information Technology', 'Quality Assurance',
|
|
36
|
+
];
|
|
37
|
+
const TAGS = [
|
|
38
|
+
'technology', 'programming', 'ai', 'productivity', 'design', 'lifestyle',
|
|
39
|
+
'business', 'startup', 'health', 'fitness', 'travel', 'food', 'gaming',
|
|
40
|
+
'finance', 'education', 'news', 'minimalism', 'remote-work', 'trending', 'featured',
|
|
41
|
+
];
|
|
42
|
+
const PRODUCTS = [
|
|
43
|
+
'Wireless Noise-Canceling Headphones', 'Mechanical Gaming Keyboard', 'Ultra-Wide 4K Gaming Monitor',
|
|
44
|
+
'Stainless Steel Insulated Water Bottle', 'Smart Fitness Watch Series 5', 'Waterproof Portable Bluetooth Speaker',
|
|
45
|
+
'Fast USB-C Multi-Port Charging Hub', 'Organic Cotton Crewneck T-Shirt', 'Minimalist RFID-Blocking Leather Wallet',
|
|
46
|
+
'Ceramic Pour-Over Coffee Dripper', 'Anti-Blue Light Computer Glasses', 'Compact High-Capacity Power Bank 20000mAh',
|
|
47
|
+
'HEPA Air Purifier for Home', 'Memory Foam Ergonomic Travel Pillow', 'Professional High-Carbon Chef Knife',
|
|
48
|
+
'Adjustable Standing Desk Converter', 'Dimmable LED Desk Lamp with Wireless Charger', 'Waterproof Trail Running Backpack',
|
|
49
|
+
];
|
|
50
|
+
const BRANDS = [
|
|
51
|
+
'Apple', 'Samsung', 'Sony', 'Nike', 'Adidas', 'Logitech', 'Anker', 'Bose',
|
|
52
|
+
'Dell', 'Asus', 'Dyson', 'Philips', 'Lenovo', 'Canon', 'LG', 'Google',
|
|
53
|
+
];
|
|
54
|
+
const STATUSES = ['active', 'inactive', 'pending', 'draft', 'archived', 'published', 'completed'];
|
|
55
|
+
|
|
56
|
+
const int = (min, max) => {
|
|
57
|
+
const lo = Math.ceil(Math.min(Number(min) || 0, Number(max) || 0));
|
|
58
|
+
const hi = Math.floor(Math.max(Number(min) || 0, Number(max) || 0));
|
|
59
|
+
return lo >= hi ? lo : lo + crypto.randomInt(hi - lo + 1);
|
|
60
|
+
};
|
|
61
|
+
const pick = (list) => list[crypto.randomInt(list.length)];
|
|
62
|
+
const cap = (s) => s[0].toUpperCase() + s.slice(1);
|
|
63
|
+
const slugify = (s) => String(s).toLowerCase().normalize('NFKD').replace(/[\u0300-\u036f]/g, '').replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '');
|
|
64
|
+
const dotSlug = (s) => String(s).toLowerCase().normalize('NFKD').replace(/[\u0300-\u036f]/g, '').replace(/[^a-z0-9]+/g, '.').replace(/^\.+|\.+$/g, '');
|
|
65
|
+
|
|
66
|
+
function makeFake() {
|
|
67
|
+
const f = {
|
|
68
|
+
number: (min = 0, max = 9999) => int(min, max),
|
|
69
|
+
float: (min = 0, max = 1000, digits = 2) => Number((min + Math.random() * (max - min)).toFixed(digits)),
|
|
70
|
+
boolean: (chance = 50) => crypto.randomInt(100) < chance,
|
|
71
|
+
pick, oneOf: pick,
|
|
72
|
+
some: (list, n = 2) => [...list].sort(() => Math.random() - 0.5).slice(0, n),
|
|
73
|
+
firstName: () => pick(FIRST),
|
|
74
|
+
lastName: () => pick(LAST),
|
|
75
|
+
name: () => `${pick(FIRST)} ${pick(LAST)}`,
|
|
76
|
+
userName: () => dotSlug(`${pick(FIRST)}${int(1, 999)}`),
|
|
77
|
+
email: () => `${dotSlug(pick(FIRST))}.${dotSlug(pick(LAST))}${int(1, 9999)}@${pick(DOMAINS)}`,
|
|
78
|
+
safeEmail: () => f.email(),
|
|
79
|
+
phone: () => `+252 6${int(1, 9)} ${int(100, 999)} ${int(1000, 9999)}`,
|
|
80
|
+
city: () => pick(CITIES),
|
|
81
|
+
country: () => pick(COUNTRIES),
|
|
82
|
+
address: () => `${int(1, 999)} ${pick(WORDS)} ${pick(['Road', 'Street', 'Avenue'])}, ${pick(CITIES)}`,
|
|
83
|
+
company: () => `${pick(COMPANIES)} ${pick(SUFFIX)}`,
|
|
84
|
+
category: () => pick(CATEGORIES),
|
|
85
|
+
department: () => pick(DEPARTMENTS),
|
|
86
|
+
product: () => pick(PRODUCTS),
|
|
87
|
+
productName: () => pick(PRODUCTS),
|
|
88
|
+
tag: () => pick(TAGS),
|
|
89
|
+
brand: () => pick(BRANDS),
|
|
90
|
+
sku: (prefix = 'SKU') => `${prefix}-${int(1000, 9999)}-${pick(['A', 'B', 'X', 'PRO', 'PLUS'])}`,
|
|
91
|
+
price: (min = 9.99, max = 499.99) => Number((min + Math.random() * (max - min)).toFixed(2)),
|
|
92
|
+
status: (customList) => pick(Array.isArray(customList) && customList.length ? customList : STATUSES),
|
|
93
|
+
word: () => pick(WORDS),
|
|
94
|
+
words: (n = 3) => Array.from({ length: n }, () => pick(WORDS)).join(' '),
|
|
95
|
+
sentence: (n = int(6, 12)) => cap(f.words(n)) + '.',
|
|
96
|
+
paragraph: (n = int(3, 6)) => Array.from({ length: n }, () => f.sentence()).join(' '),
|
|
97
|
+
paragraphs: (n = 3) => Array.from({ length: n }, () => f.paragraph()).join('\n\n'),
|
|
98
|
+
text: (max = 200) => f.paragraph().slice(0, max),
|
|
99
|
+
title: () => cap(f.words(int(2, 5))),
|
|
100
|
+
slug: (arg = 3) => {
|
|
101
|
+
if (typeof arg === 'string') return slugify(arg);
|
|
102
|
+
const n = typeof arg === 'number' ? arg : 3;
|
|
103
|
+
return slugify(f.words(n));
|
|
104
|
+
},
|
|
105
|
+
smart: (col, modelName = '') => {
|
|
106
|
+
const c = String(col || '').toLowerCase();
|
|
107
|
+
const m = String(modelName || '').toLowerCase();
|
|
108
|
+
if (c === 'name' || c === 'title') {
|
|
109
|
+
if (m.includes('category')) return f.category();
|
|
110
|
+
if (m.includes('department')) return f.department();
|
|
111
|
+
if (m.includes('product') || m.includes('item')) return f.product();
|
|
112
|
+
if (m.includes('tag')) return f.tag();
|
|
113
|
+
if (m.includes('brand') || m.includes('company')) return f.company();
|
|
114
|
+
if (m.includes('post') || m.includes('article')) return f.title();
|
|
115
|
+
return f.name();
|
|
116
|
+
}
|
|
117
|
+
if (c === 'slug') {
|
|
118
|
+
if (m.includes('category')) return slugify(f.category());
|
|
119
|
+
if (m.includes('tag')) return slugify(f.tag());
|
|
120
|
+
if (m.includes('product')) return slugify(f.product());
|
|
121
|
+
return f.slug();
|
|
122
|
+
}
|
|
123
|
+
if (c === 'price' || c === 'cost' || c === 'amount') return f.price();
|
|
124
|
+
if (c === 'sku' || c === 'code') return f.sku();
|
|
125
|
+
if (c === 'status') return f.status();
|
|
126
|
+
if (c.includes('email')) return f.email();
|
|
127
|
+
if (c.includes('phone')) return f.phone();
|
|
128
|
+
if (c.includes('city')) return f.city();
|
|
129
|
+
if (c.includes('country')) return f.country();
|
|
130
|
+
if (c.includes('address')) return f.address();
|
|
131
|
+
if (c.includes('image') || c.includes('avatar')) return f.imageUrl();
|
|
132
|
+
if (c.includes('description') || c.includes('summary')) return f.sentence();
|
|
133
|
+
if (c.includes('content') || c.includes('body')) return f.paragraph();
|
|
134
|
+
if (c.startsWith('is_') || c.startsWith('has_')) return true;
|
|
135
|
+
return f.word();
|
|
136
|
+
},
|
|
137
|
+
url: () => `https://${pick(DOMAINS)}/${f.slug(2)}`,
|
|
138
|
+
imageUrl: (w = 640, h = 480) => `https://picsum.photos/seed/${int(1, 100000)}/${w}/${h}`,
|
|
139
|
+
color: () => '#' + crypto.randomBytes(3).toString('hex'),
|
|
140
|
+
uuid: () => crypto.randomUUID(),
|
|
141
|
+
password: (n = 12) => crypto.randomBytes(n).toString('base64url').slice(0, n),
|
|
142
|
+
// dates as 'YYYY-MM-DD HH:MM:SS' (how the database keeps them)
|
|
143
|
+
date: (from = '-1 year', to = 'now') => {
|
|
144
|
+
const UNITS = { second: 1e3, minute: 6e4, hour: 36e5, day: 864e5, week: 6048e5, month: 2592e6, year: 31536e6 };
|
|
145
|
+
const span = (s) => {
|
|
146
|
+
if (s instanceof Date) return s.getTime();
|
|
147
|
+
if (typeof s === 'number' && Number.isFinite(s)) return s;
|
|
148
|
+
const str = String(s || 'now').trim();
|
|
149
|
+
if (str === 'now') return Date.now();
|
|
150
|
+
const numMatch = str.match(/-?\d+/);
|
|
151
|
+
const unitMatch = str.match(/second|minute|hour|day|week|month|year/i);
|
|
152
|
+
if (numMatch && unitMatch) {
|
|
153
|
+
return Date.now() + Number(numMatch[0]) * UNITS[unitMatch[0].toLowerCase()];
|
|
154
|
+
}
|
|
155
|
+
const parsed = Date.parse(str);
|
|
156
|
+
return Number.isNaN(parsed) ? Date.now() : parsed;
|
|
157
|
+
};
|
|
158
|
+
const t = int(Math.min(span(from), span(to)), Math.max(span(from), span(to)));
|
|
159
|
+
return new Date(t).toISOString().slice(0, 19).replace('T', ' ');
|
|
160
|
+
},
|
|
161
|
+
pastDate: () => f.date('-1 year', 'now'),
|
|
162
|
+
futureDate: () => f.date('now', '+1 year'),
|
|
163
|
+
};
|
|
164
|
+
// fake.unique().email(): tries again until the value is new
|
|
165
|
+
let seen = new Map();
|
|
166
|
+
f.unique = () => new Proxy({}, {
|
|
167
|
+
get(_, name) {
|
|
168
|
+
if (name === 'reset') return () => { seen = new Map(); };
|
|
169
|
+
return (...args) => {
|
|
170
|
+
const set = seen.get(name) || new Set();
|
|
171
|
+
seen.set(name, set);
|
|
172
|
+
for (let i = 0; i < 1000; i++) { const v = f[name](...args); if (!set.has(v)) { set.add(v); return v; } }
|
|
173
|
+
throw new Error(`fake.unique().${String(name)}() ran out of new values`);
|
|
174
|
+
};
|
|
175
|
+
},
|
|
176
|
+
});
|
|
177
|
+
return f;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
module.exports = { fake: makeFake(), makeFake };
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Form requests and API resources: validation and JSON transformation.
|
|
3
|
+
*
|
|
4
|
+
* // app/Http/Requests/StorePostRequest.js
|
|
5
|
+
* class StorePostRequest extends FormRequest {
|
|
6
|
+
* authorize(req) { return req.user != null } // false → 403
|
|
7
|
+
* rules(req) { return { title: 'required|max:200', body: 'required' } }
|
|
8
|
+
* messages() { return { 'title.required': 'Give the post a title.' } }
|
|
9
|
+
* prepareForValidation(data) { return { ...data, title: String(data.title || '').trim() } }
|
|
10
|
+
* }
|
|
11
|
+
* const data = await StorePostRequest.validate(req) // in a controller
|
|
12
|
+
*
|
|
13
|
+
* // app/Http/Resources/PostResource.js
|
|
14
|
+
* class PostResource extends JsonResource {
|
|
15
|
+
* toArray(req) { return { id: this.id, title: this.title, author: new UserResource(this.user), comments: this.whenLoaded('comments') } }
|
|
16
|
+
* }
|
|
17
|
+
* return new PostResource(post) // { data: { … } }
|
|
18
|
+
* return PostResource.collection(posts) // { data: [ … ] } (a paginate() result keeps its meta)
|
|
19
|
+
*/
|
|
20
|
+
const { HttpError } = require('./http.js');
|
|
21
|
+
|
|
22
|
+
class FormRequest {
|
|
23
|
+
constructor(req = null) {
|
|
24
|
+
this.req = req;
|
|
25
|
+
this._validated = null;
|
|
26
|
+
}
|
|
27
|
+
user() {
|
|
28
|
+
return this.req ? this.req.user : null;
|
|
29
|
+
}
|
|
30
|
+
validated(key = null, fallback = null) {
|
|
31
|
+
const data = this._validated || (this.req && this.req.validated) || {};
|
|
32
|
+
if (key == null) return data;
|
|
33
|
+
return Object.prototype.hasOwnProperty.call(data, key) ? data[key] : fallback;
|
|
34
|
+
}
|
|
35
|
+
authorize() { return true; }
|
|
36
|
+
rules() { return {}; }
|
|
37
|
+
messages() { return {}; }
|
|
38
|
+
attributes() { return {}; }
|
|
39
|
+
prepareForValidation(data) { return data; }
|
|
40
|
+
static async validate(req) {
|
|
41
|
+
const f = new this(req);
|
|
42
|
+
if (!(await f.authorize(req))) throw new HttpError(403, 'This action is unauthorized.');
|
|
43
|
+
const prepared = await f.prepareForValidation({ ...(req && req.body && typeof req.body === 'object' ? req.body : {}) });
|
|
44
|
+
if (prepared && typeof prepared === 'object' && req) req.body = prepared;
|
|
45
|
+
const validated = await req.validate(await f.rules(req), f.messages(), f.attributes());
|
|
46
|
+
f._validated = validated;
|
|
47
|
+
if (req) {
|
|
48
|
+
req.validated = validated;
|
|
49
|
+
req._validated = validated;
|
|
50
|
+
req.formRequest = f;
|
|
51
|
+
}
|
|
52
|
+
return validated;
|
|
53
|
+
}
|
|
54
|
+
static handle(req, res, next) {
|
|
55
|
+
return Promise.resolve()
|
|
56
|
+
.then(() => this.validate(req))
|
|
57
|
+
.then(() => { if (typeof next === 'function') next(); })
|
|
58
|
+
.catch((err) => {
|
|
59
|
+
if (typeof next === 'function') next(err);
|
|
60
|
+
else throw err;
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
const MISSING = Symbol('missing');
|
|
66
|
+
class JsonResource {
|
|
67
|
+
static wrap = 'data';
|
|
68
|
+
constructor(resource) { this.resource = resource; return new Proxy(this, { get: (t, k) => (k in t ? t[k] : t.resource == null ? undefined : t.resource[k]) }); }
|
|
69
|
+
toArray() { return this.resource && typeof this.resource.toJSON === 'function' ? this.resource.toJSON() : this.resource; }
|
|
70
|
+
// only when the relation was loaded with with(…)
|
|
71
|
+
whenLoaded(name, value) { const r = this.resource; return r && r.__relations && r.__relations[name] ? (value === undefined ? r[name] : value) : MISSING; }
|
|
72
|
+
when(condition, value) { return condition ? (typeof value === 'function' ? value() : value) : MISSING; }
|
|
73
|
+
resolve(req) { return clean(this.resource == null ? null : this.toArray(req)); }
|
|
74
|
+
toJSON() { const W = this.constructor.wrap; const data = this.resolve(null); return W ? { [W]: data } : data; }
|
|
75
|
+
static collection(items) { return new ResourceCollection(items, this); }
|
|
76
|
+
static make(resource) { return new this(resource); }
|
|
77
|
+
}
|
|
78
|
+
class ResourceCollection {
|
|
79
|
+
constructor(items, Resource) { this.items = items; this.Resource = Resource; }
|
|
80
|
+
toJSON() {
|
|
81
|
+
const paged = this.items && !Array.isArray(this.items) && Array.isArray(this.items.data);
|
|
82
|
+
const list = (paged ? this.items.data : this.items || []).map((x) => new this.Resource(x).resolve(null));
|
|
83
|
+
if (!paged) return { data: list };
|
|
84
|
+
const { data, ...meta } = this.items;
|
|
85
|
+
return { data: list, meta };
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
// leaves out whenLoaded()/when() values that aren't there; resources inside resources become their data
|
|
89
|
+
function clean(v) {
|
|
90
|
+
if (v === MISSING) return MISSING;
|
|
91
|
+
if (v instanceof JsonResource) return v.resolve(null);
|
|
92
|
+
if (v instanceof ResourceCollection) return v.toJSON().data;
|
|
93
|
+
if (Array.isArray(v)) return v.map(clean).filter((x) => x !== MISSING);
|
|
94
|
+
if (v && typeof v === 'object' && !(v instanceof Date) && v.constructor === Object) {
|
|
95
|
+
const out = {};
|
|
96
|
+
for (const [k, x] of Object.entries(v)) { const c = clean(x); if (c !== MISSING) out[k] = c; }
|
|
97
|
+
return out;
|
|
98
|
+
}
|
|
99
|
+
return v;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
module.exports = { FormRequest, JsonResource, ResourceCollection };
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Gates and policies: authorization and permissions.
|
|
3
|
+
*
|
|
4
|
+
* Gate.define('edit-settings', (user) => user.is_admin)
|
|
5
|
+
* // app/Policies/PostPolicy.js — found by itself for the Post model
|
|
6
|
+
* class PostPolicy {
|
|
7
|
+
* before(user) { if (user.is_admin) return true } // optional: say yes (or no) to everything first
|
|
8
|
+
* view(user, post) { return true }
|
|
9
|
+
* update(user, post) { return post.user_id === user.id }
|
|
10
|
+
* delete(user, post) { return post.user_id === user.id }
|
|
11
|
+
* create(user) { return user.email_verified_at != null }
|
|
12
|
+
* }
|
|
13
|
+
*
|
|
14
|
+
* await req.authorize('update', post) // 403 when not allowed
|
|
15
|
+
* if (await req.can('delete', post)) { … }
|
|
16
|
+
* Route.put('/posts/{post}', …).middleware('can:update,post')
|
|
17
|
+
* await Gate.forUser(user).allows('create', Post)
|
|
18
|
+
*/
|
|
19
|
+
const path = require('path');
|
|
20
|
+
const gates = new Map();
|
|
21
|
+
let policyFiles = new Map(); // model name → file
|
|
22
|
+
|
|
23
|
+
const unwrap = (m) => (m && m.default ? m.default : m);
|
|
24
|
+
const modelName = (target) => (typeof target === 'function' ? target.name : target && target.constructor ? target.constructor.name : null);
|
|
25
|
+
|
|
26
|
+
function hasPolicyMethod(policy, method) {
|
|
27
|
+
if (!policy || typeof method !== 'string' || !method) return false;
|
|
28
|
+
if (method === 'constructor' || method === '__proto__' || method === 'prototype') return false;
|
|
29
|
+
if (Object.prototype.hasOwnProperty.call(policy, method) && typeof policy[method] === 'function') return true;
|
|
30
|
+
let proto = Object.getPrototypeOf(policy);
|
|
31
|
+
while (proto && proto !== Object.prototype) {
|
|
32
|
+
if (Object.prototype.hasOwnProperty.call(proto, method) && typeof policy[method] === 'function') return true;
|
|
33
|
+
proto = Object.getPrototypeOf(proto);
|
|
34
|
+
}
|
|
35
|
+
return false;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
async function check(user, ability, args) {
|
|
39
|
+
if (!ability || typeof ability !== 'string' || ability === 'constructor' || ability === '__proto__' || ability === 'prototype') {
|
|
40
|
+
return false;
|
|
41
|
+
}
|
|
42
|
+
const target = args[0];
|
|
43
|
+
const name = target != null && typeof target !== 'string' ? modelName(target) : null;
|
|
44
|
+
const file = name && policyFiles.get(name);
|
|
45
|
+
if (file) {
|
|
46
|
+
const Policy = typeof file === 'string' ? unwrap(require(file)) : file;
|
|
47
|
+
const policy = typeof Policy === 'function' ? new Policy() : Policy;
|
|
48
|
+
if (hasPolicyMethod(policy, 'before') && (user != null || policy.before.allowGuest)) {
|
|
49
|
+
const b = await policy.before(user, ability, ...args);
|
|
50
|
+
if (b === true || b === false) return b;
|
|
51
|
+
}
|
|
52
|
+
if (hasPolicyMethod(policy, ability)) {
|
|
53
|
+
if (user == null && !policy[ability].allowGuest) return false;
|
|
54
|
+
return Boolean(await policy[ability](user, ...(typeof target === 'function' ? args.slice(1) : args)));
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
const fn = gates.get(ability);
|
|
58
|
+
if (fn) return user != null || fn.allowGuest ? Boolean(await fn(user, ...args)) : false;
|
|
59
|
+
return false; // nothing says yes: no
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const Gate = {
|
|
63
|
+
define(ability, fn) { gates.set(ability, fn); },
|
|
64
|
+
policy(ModelOrName, Policy) { policyFiles.set(typeof ModelOrName === 'string' ? ModelOrName : ModelOrName.name, Policy); },
|
|
65
|
+
policyFile(name, file) { policyFiles.set(name, file); },
|
|
66
|
+
resetPolicies() { policyFiles = new Map(); },
|
|
67
|
+
has: (ability) => gates.has(ability),
|
|
68
|
+
forUser(user) {
|
|
69
|
+
return {
|
|
70
|
+
allows: (ability, ...args) => check(user, ability, args),
|
|
71
|
+
denies: async (ability, ...args) => !(await check(user, ability, args)),
|
|
72
|
+
authorize: async (ability, ...args) => { if (!(await check(user, ability, args))) { const { HttpError } = require('./http.js'); throw new HttpError(403, 'This action is unauthorized.'); } return true; },
|
|
73
|
+
};
|
|
74
|
+
},
|
|
75
|
+
abilities: () => [...gates.keys()],
|
|
76
|
+
policies: () => [...policyFiles.keys()].map((k) => ({ model: k, policy: typeof policyFiles.get(k) === 'string' ? path.basename(policyFiles.get(k)) : policyFiles.get(k).name })),
|
|
77
|
+
};
|
|
78
|
+
|
|
79
|
+
module.exports = { Gate, check };
|