@things-factory/integration-base 9.0.0-beta.79 → 9.0.0-beta.80
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/dist-server/controllers/publish-data.js +7 -2
- package/dist-server/controllers/publish-data.js.map +1 -1
- package/dist-server/engine/analyzer/analyze-integration.js +1 -1
- package/dist-server/engine/analyzer/analyze-integration.js.map +1 -1
- package/dist-server/engine/connection-manager.js +41 -33
- package/dist-server/engine/connection-manager.js.map +1 -1
- package/dist-server/engine/connector/graphql-connector.js +4 -1
- package/dist-server/engine/connector/graphql-connector.js.map +1 -1
- package/dist-server/engine/connector/headless-connector.js +1 -2
- package/dist-server/engine/connector/headless-connector.js.map +1 -1
- package/dist-server/engine/connector/http-connector.js +5 -1
- package/dist-server/engine/connector/http-connector.js.map +1 -1
- package/dist-server/engine/connector/operato-connector.js +10 -8
- package/dist-server/engine/connector/operato-connector.js.map +1 -1
- package/dist-server/engine/connector/oracle-connector.js +2 -2
- package/dist-server/engine/connector/oracle-connector.js.map +1 -1
- package/dist-server/engine/connector/postgresql-connector.js +3 -3
- package/dist-server/engine/connector/postgresql-connector.js.map +1 -1
- package/dist-server/engine/connector/proxy-connector.js +1 -1
- package/dist-server/engine/connector/proxy-connector.js.map +1 -1
- package/dist-server/engine/scenario-engine.js +10 -7
- package/dist-server/engine/scenario-engine.js.map +1 -1
- package/dist-server/engine/task/headless-post.js +3 -1
- package/dist-server/engine/task/headless-post.js.map +1 -1
- package/dist-server/engine/task/headless-scrap.js +36 -4
- package/dist-server/engine/task/headless-scrap.js.map +1 -1
- package/dist-server/engine/task/http-get.js +4 -1
- package/dist-server/engine/task/http-get.js.map +1 -1
- package/dist-server/engine/task/http-post.js +4 -1
- package/dist-server/engine/task/http-post.js.map +1 -1
- package/dist-server/engine/task/mqtt-subscribe.js +9 -11
- package/dist-server/engine/task/mqtt-subscribe.js.map +1 -1
- package/dist-server/engine/task/mssql-procedure.js +1 -1
- package/dist-server/engine/task/mssql-procedure.js.map +1 -1
- package/dist-server/engine/task/oracle-procedure.js +10 -10
- package/dist-server/engine/task/oracle-procedure.js.map +1 -1
- package/dist-server/engine/task/pick-pending-scenario.js +5 -1
- package/dist-server/engine/task/pick-pending-scenario.js.map +1 -1
- package/dist-server/engine/task/state-group-read.js +1 -2
- package/dist-server/engine/task/state-group-read.js.map +1 -1
- package/dist-server/engine/task/state-read.js +1 -2
- package/dist-server/engine/task/state-read.js.map +1 -1
- package/dist-server/engine/task/state-write.js +1 -2
- package/dist-server/engine/task/state-write.js.map +1 -1
- package/dist-server/engine/task/stop-scenario.js +3 -3
- package/dist-server/engine/task/stop-scenario.js.map +1 -1
- package/dist-server/engine/task/sub-scenario.js +5 -2
- package/dist-server/engine/task/sub-scenario.js.map +1 -1
- package/dist-server/engine/task/switch-range-scenario.js +5 -2
- package/dist-server/engine/task/switch-range-scenario.js.map +1 -1
- package/dist-server/engine/task/switch-scenario.js +5 -2
- package/dist-server/engine/task/switch-scenario.js.map +1 -1
- package/dist-server/engine/task/variables.js +1 -1
- package/dist-server/engine/task/variables.js.map +1 -1
- package/dist-server/engine/task-registry.js +4 -2
- package/dist-server/engine/task-registry.js.map +1 -1
- package/dist-server/routers/scenario-schedule-callback-router.js +2 -2
- package/dist-server/routers/scenario-schedule-callback-router.js.map +1 -1
- package/dist-server/service/connection/connection-mutation.js +46 -12
- package/dist-server/service/connection/connection-mutation.js.map +1 -1
- package/dist-server/service/connection/connection-query.js +9 -3
- package/dist-server/service/connection/connection-query.js.map +1 -1
- package/dist-server/service/connection/connection-subscription.js +10 -8
- package/dist-server/service/connection/connection-subscription.js.map +1 -1
- package/dist-server/service/connection/connection-type.js +4 -1
- package/dist-server/service/connection/connection-type.js.map +1 -1
- package/dist-server/service/payload-log/payload-log-mutation.js +25 -7
- package/dist-server/service/payload-log/payload-log-mutation.js.map +1 -1
- package/dist-server/service/scenario/scenario-mutation.js +56 -12
- package/dist-server/service/scenario/scenario-mutation.js.map +1 -1
- package/dist-server/service/scenario/scenario-query.js +2 -3
- package/dist-server/service/scenario/scenario-query.js.map +1 -1
- package/dist-server/service/scenario/scenario.js +5 -5
- package/dist-server/service/scenario/scenario.js.map +1 -1
- package/dist-server/service/scenario-instance/scenario-instance-subscription.js +6 -8
- package/dist-server/service/scenario-instance/scenario-instance-subscription.js.map +1 -1
- package/dist-server/service/scenario-instance/scenario-instance-type.js +26 -23
- package/dist-server/service/scenario-instance/scenario-instance-type.js.map +1 -1
- package/dist-server/service/scenario-queue/scenario-queue-subscription.js +3 -4
- package/dist-server/service/scenario-queue/scenario-queue-subscription.js.map +1 -1
- package/dist-server/service/state-register/data-resolver.js +3 -4
- package/dist-server/service/state-register/data-resolver.js.map +1 -1
- package/dist-server/service/state-register/state-register-mutation.js +32 -9
- package/dist-server/service/state-register/state-register-mutation.js.map +1 -1
- package/dist-server/service/state-register/state-register-query.js +1 -1
- package/dist-server/service/state-register/state-register-query.js.map +1 -1
- package/dist-server/service/step/step-mutation.js +9 -3
- package/dist-server/service/step/step-mutation.js.map +1 -1
- package/dist-server/tsconfig.tsbuildinfo +1 -1
- package/helps/integration/task/headless-scrap.ja.md +11 -4
- package/helps/integration/task/headless-scrap.ko.md +12 -5
- package/helps/integration/task/headless-scrap.md +10 -3
- package/helps/integration/task/headless-scrap.ms.md +9 -2
- package/helps/integration/task/headless-scrap.zh.md +9 -2
- package/package.json +2 -2
- package/translations/en.json +3 -1
- package/translations/ja.json +3 -1
- package/translations/ko.json +3 -1
- package/translations/ms.json +3 -1
- package/translations/zh.json +3 -1
@@ -6,10 +6,15 @@ const state_register_1 = require("../service/state-register/state-register");
|
|
6
6
|
async function publishData(tag, data, { domain, user }) {
|
7
7
|
const repository = (0, shell_1.getRepository)(state_register_1.StateRegister);
|
8
8
|
const stateRegister = await repository.findOne({
|
9
|
-
where: { domain: { id: domain
|
9
|
+
where: { domain: { id: domain?.id }, name: tag }
|
10
10
|
});
|
11
11
|
if (stateRegister) {
|
12
|
-
await repository.save(
|
12
|
+
await repository.save({
|
13
|
+
...stateRegister,
|
14
|
+
state: data,
|
15
|
+
writer: user,
|
16
|
+
wroteAt: new Date()
|
17
|
+
});
|
13
18
|
}
|
14
19
|
shell_1.pubsub.publish('data', {
|
15
20
|
data: {
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"publish-data.js","sourceRoot":"","sources":["../../server/controllers/publish-data.ts"],"names":[],"mappings":";;AAKA,kCAuBC;AA5BD,iDAAqE;AAGrE,6EAAwE;AAEjE,KAAK,UAAU,WAAW,CAAC,GAAW,EAAE,IAAS,EAAE,EAAE,MAAM,EAAE,IAAI,EAAkC;IACxG,MAAM,UAAU,GAAG,IAAA,qBAAa,EAAC,8BAAa,CAAC,CAAA;IAE/C,MAAM,aAAa,GAAG,MAAM,UAAU,CAAC,OAAO,CAAC;QAC7C,KAAK,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,EAAE,MAAM,
|
1
|
+
{"version":3,"file":"publish-data.js","sourceRoot":"","sources":["../../server/controllers/publish-data.ts"],"names":[],"mappings":";;AAKA,kCAuBC;AA5BD,iDAAqE;AAGrE,6EAAwE;AAEjE,KAAK,UAAU,WAAW,CAAC,GAAW,EAAE,IAAS,EAAE,EAAE,MAAM,EAAE,IAAI,EAAkC;IACxG,MAAM,UAAU,GAAG,IAAA,qBAAa,EAAC,8BAAa,CAAC,CAAA;IAE/C,MAAM,aAAa,GAAG,MAAM,UAAU,CAAC,OAAO,CAAC;QAC7C,KAAK,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,EAAE,IAAI,EAAE,GAAG,EAAE;KACjD,CAAC,CAAA;IAEF,IAAI,aAAa,EAAE,CAAC;QAClB,MAAM,UAAU,CAAC,IAAI,CAAC;YACpB,GAAG,aAAa;YAChB,KAAK,EAAE,IAAI;YACX,MAAM,EAAE,IAAI;YACZ,OAAO,EAAE,IAAI,IAAI,EAAE;SACpB,CAAC,CAAA;IACJ,CAAC;IAED,cAAM,CAAC,OAAO,CAAC,MAAM,EAAE;QACrB,IAAI,EAAE;YACJ,MAAM;YACN,GAAG;YACH,IAAI;SACL;KACF,CAAC,CAAA;AACJ,CAAC","sourcesContent":["import { Domain, getRepository, pubsub } from '@things-factory/shell'\nimport { User } from '@things-factory/auth-base'\n\nimport { StateRegister } from '../service/state-register/state-register'\n\nexport async function publishData(tag: string, data: any, { domain, user }: { domain: Domain; user: User }) {\n const repository = getRepository(StateRegister)\n\n const stateRegister = await repository.findOne({\n where: { domain: { id: domain?.id }, name: tag }\n })\n\n if (stateRegister) {\n await repository.save({\n ...stateRegister,\n state: data,\n writer: user,\n wroteAt: new Date()\n })\n }\n\n pubsub.publish('data', {\n data: {\n domain,\n tag,\n data\n }\n })\n}\n"]}
|
@@ -63,7 +63,7 @@ async function analyzeIntegration(domain) {
|
|
63
63
|
scenarios.forEach(scenario => {
|
64
64
|
const tags = (0, uniq_1.default)(scenario.steps
|
65
65
|
.filter(step => !step.connection && step.task == 'publish')
|
66
|
-
.map(step =>
|
66
|
+
.map(step => step.params?.tag)
|
67
67
|
.filter(Boolean));
|
68
68
|
for (const tag of tags) {
|
69
69
|
if (tagNames.includes(tag)) {
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"analyze-integration.js","sourceRoot":"","sources":["../../../server/engine/analyzer/analyze-integration.ts"],"names":[],"mappings":";;AAMA,gDA4GC;;AAlHD,+DAA8B;AAE9B,iDAA6D;AAC7D,8DAA0D;AAC1D,8EAAqE;AAE9D,KAAK,UAAU,kBAAkB,CAAC,MAAc;IACrD,MAAM,QAAQ,GAAG,EAAE,CAAA;IAEnB,MAAM,KAAK,GAAG;QACZ,KAAK,EAAE,EAAE;QACT,aAAa,EAAE,EAAE;KAClB,CAAA;IAED,IAAI,EAAE,GAAG,CAAC,CAAA;IAEV,MAAM,SAAS,GAAG,MAAM,IAAA,qBAAa,EAAC,mBAAQ,CAAC,CAAC,IAAI,CAAC;QACnD,KAAK,EAAE,EAAE,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SAAQ;YACV,CAAC;YAED,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC;gBACf,EAAE,EAAE,OAAO,GAAG,EAAE;gBAChB,MAAM,EAAE,CAAC,KAAK,CAAC;gBACf,IAAI,EAAE,GAAG;gBACT,IAAI,EAAE,OAAO;gBACb,UAAU,EAAE;oBACV,GAAG;iBACJ;aACF,CAAC,CAAA;YAEF,QAAQ,CAAC,IAAI,CAAC,GAAG,CAAC,CAAA;QACpB,CAAC;QAED,MAAM,aAAa,GAAG,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE;YACnC,OAAO;gBACL,EAAE,EAAE,EAAE,EAAE;gBACR,IAAI,EAAE,SAAS;gBACf,SAAS,EAAE,QAAQ,CAAC,EAAE;gBACtB,OAAO,EAAE,OAAO,GAAG,EAAE;gBACrB,UAAU,EAAE,EAAE;aACf,CAAA;QACH,CAAC,CAAC,CAAA;QAEF,KAAK,CAAC,aAAa,GAAG,KAAK,CAAC,aAAa,CAAC,MAAM,CAAC,aAAa,CAAC,CAAA;IACjE,CAAC,CAAC,CAAA;IAEF,OAAO,KAAK,CAAA;AACd,CAAC","sourcesContent":["import uniq from 'lodash/uniq'\n\nimport { Domain, getRepository } from '@things-factory/shell'\nimport { Scenario } from '../../service/scenario/scenario'\nimport { Connection } from '../../service/connection/connection-type'\n\nexport async function analyzeIntegration(domain: Domain) {\n const tagNames = []\n\n const model = {\n nodes: [],\n relationships: []\n }\n\n var id = 0\n\n const scenarios = await getRepository(Scenario).find({\n where: { domain: { id: domain.id } },\n relations: ['steps']\n })\n\n const connections = await getRepository(Connection).find({\n where: { domain: { id: domain.id } }\n })\n\n model.nodes = model.nodes.concat(\n scenarios.map(scenario => {\n return {\n id: scenario.id,\n labels: ['Scenario'],\n text: scenario.name,\n icon: 'settings',\n properties: {\n name: scenario.name,\n description: scenario.description\n }\n }\n })\n )\n\n model.nodes = model.nodes.concat(\n connections.map(connection => {\n return {\n id: connection.id,\n labels: ['Connection'],\n text: connection.name,\n icon: 'link',\n properties: {\n name: connection.name,\n description: connection.description\n }\n }\n })\n )\n\n scenarios.forEach(scenario => {\n const connectionNames = uniq(scenario.steps.map(step => step.connection).filter(Boolean))\n const connectionList = connectionNames\n .map(connectionName => connections.find(connection => connection.name == connectionName))\n .filter(Boolean)\n\n const relationships = connectionList.map(connection => {\n return {\n id: ++id,\n type: 'using',\n startNode: scenario.id,\n endNode: connection.id,\n properties: {}\n }\n })\n\n model.relationships = model.relationships.concat(relationships)\n })\n\n scenarios.forEach(scenario => {\n const tags = uniq(\n scenario.steps\n .filter(step => !step.connection && step.task == 'publish')\n .map(step => step.params?.tag)\n .filter(Boolean)\n )\n\n for (const tag of tags) {\n if (tagNames.includes(tag)) {\n continue\n }\n\n model.nodes.push({\n id: `tag-${tag}`,\n labels: ['Tag'],\n text: tag,\n icon: 'label',\n properties: {\n tag\n }\n })\n\n tagNames.push(tag)\n }\n\n const relationships = tags.map(tag => {\n return {\n id: ++id,\n type: 'publish',\n startNode: scenario.id,\n endNode: `tag-${tag}`,\n properties: {}\n }\n })\n\n model.relationships = model.relationships.concat(relationships)\n })\n\n return model\n}\n"]}
|
@@ -29,12 +29,37 @@ const systemTimestamp = (0, winston_1.format)((info, opts) => {
|
|
29
29
|
return info;
|
30
30
|
});
|
31
31
|
class ConnectionManager {
|
32
|
+
static { this.connectors = {}; }
|
33
|
+
static { this.connections = {}; }
|
34
|
+
static { this.entities = {}; }
|
35
|
+
static { this.logFormat = printf(({ level, message, timestamp, stack }) => {
|
36
|
+
return `${timestamp} ${level}: ${stack || message}`;
|
37
|
+
}); }
|
38
|
+
static { this.logger = (0, winston_1.createLogger)({
|
39
|
+
format: combine(errors({ stack: true }), systemTimestamp({ tz: SYSTEM_TZ }), splat(), ConnectionManager.logFormat),
|
40
|
+
transports: [
|
41
|
+
new winston_1.transports.DailyRotateFile({
|
42
|
+
filename: `logs/connections-%DATE%.log`,
|
43
|
+
datePattern: 'YYYY-MM-DD-HH',
|
44
|
+
zippedArchive: false,
|
45
|
+
maxSize: '20m',
|
46
|
+
maxFiles: '14d',
|
47
|
+
level: 'info'
|
48
|
+
}),
|
49
|
+
new shell_1.PubSubLogTransport({
|
50
|
+
topic: 'connection-log'
|
51
|
+
})
|
52
|
+
]
|
53
|
+
}); }
|
32
54
|
static async ready() {
|
33
55
|
const CONNECTIONS = (await (0, shell_1.getRepository)(service_1.Connection).find({
|
34
56
|
where: { active: true },
|
35
57
|
relations: ['domain', 'edge', 'creator', 'updater']
|
36
58
|
})).map(connection => {
|
37
|
-
return
|
59
|
+
return {
|
60
|
+
...connection,
|
61
|
+
params: connection.params || {}
|
62
|
+
};
|
38
63
|
});
|
39
64
|
ConnectionManager.logger.info('Initializing ConnectionManager...');
|
40
65
|
return await Promise.all([...Object.keys(ConnectionManager.connectors), 'proxy-connector'].map(type => {
|
@@ -70,7 +95,9 @@ class ConnectionManager {
|
|
70
95
|
return ConnectionManager.connectors[type];
|
71
96
|
}
|
72
97
|
static getConnectors() {
|
73
|
-
return
|
98
|
+
return {
|
99
|
+
...ConnectionManager.connectors
|
100
|
+
};
|
74
101
|
}
|
75
102
|
static unregisterConnector(type) {
|
76
103
|
delete ConnectionManager.connectors[type];
|
@@ -82,36 +109,39 @@ class ConnectionManager {
|
|
82
109
|
return ConnectionManager.entities;
|
83
110
|
}
|
84
111
|
static getConnectionInstance(connection) {
|
85
|
-
var _a;
|
86
112
|
const { domain, name } = connection;
|
87
|
-
return
|
113
|
+
return ConnectionManager.connections[domain.id]?.[name];
|
88
114
|
}
|
89
115
|
static getConnectionInstanceByName(domain, name) {
|
90
116
|
const connections = ConnectionManager.connections[domain.id];
|
91
|
-
const connection = connections
|
117
|
+
const connection = connections?.[name];
|
92
118
|
if (!connection) {
|
93
119
|
throw `The connection with the given name(${name}) cannot be found`;
|
94
120
|
}
|
95
121
|
return connection;
|
96
122
|
}
|
97
123
|
static getConnectionInstanceEntityByName(domain, name) {
|
98
|
-
|
99
|
-
const connection = (_a = ConnectionManager.entities[domain.id]) === null || _a === void 0 ? void 0 : _a[name];
|
124
|
+
const connection = ConnectionManager.entities[domain.id]?.[name];
|
100
125
|
if (connection) {
|
101
126
|
return connection;
|
102
127
|
}
|
103
128
|
if (domain.parentId) {
|
104
|
-
return
|
129
|
+
return ConnectionManager.entities[domain.id]?.[name];
|
105
130
|
}
|
106
131
|
}
|
107
132
|
static getConnectionInstances(domain) {
|
108
133
|
const connections = ConnectionManager.connections[domain.id];
|
109
134
|
const parentConnections = domain.parentId && ConnectionManager.connections[domain.parentId];
|
110
|
-
return
|
135
|
+
return {
|
136
|
+
...parentConnections,
|
137
|
+
...connections
|
138
|
+
};
|
111
139
|
}
|
112
140
|
static getConnectionInstanceEntities(domain) {
|
113
141
|
const connections = ConnectionManager.entities[domain.id];
|
114
|
-
return
|
142
|
+
return {
|
143
|
+
...connections
|
144
|
+
};
|
115
145
|
}
|
116
146
|
static addConnectionInstance(connection, instance) {
|
117
147
|
const { domain, name } = connection;
|
@@ -132,7 +162,7 @@ class ConnectionManager {
|
|
132
162
|
const { domain, name } = connection;
|
133
163
|
var connections = ConnectionManager.connections[domain.id];
|
134
164
|
var entities = ConnectionManager.entities[domain.id];
|
135
|
-
var instance = connections
|
165
|
+
var instance = connections?.[name];
|
136
166
|
if (!connections || !instance) {
|
137
167
|
debug('remove-connection', `'${name}' connection not found in domain '${domain.subdomain}'`);
|
138
168
|
return;
|
@@ -160,26 +190,4 @@ class ConnectionManager {
|
|
160
190
|
}
|
161
191
|
}
|
162
192
|
exports.ConnectionManager = ConnectionManager;
|
163
|
-
ConnectionManager.connectors = {};
|
164
|
-
ConnectionManager.connections = {};
|
165
|
-
ConnectionManager.entities = {};
|
166
|
-
ConnectionManager.logFormat = printf(({ level, message, timestamp, stack }) => {
|
167
|
-
return `${timestamp} ${level}: ${stack || message}`;
|
168
|
-
});
|
169
|
-
ConnectionManager.logger = (0, winston_1.createLogger)({
|
170
|
-
format: combine(errors({ stack: true }), systemTimestamp({ tz: SYSTEM_TZ }), splat(), ConnectionManager.logFormat),
|
171
|
-
transports: [
|
172
|
-
new winston_1.transports.DailyRotateFile({
|
173
|
-
filename: `logs/connections-%DATE%.log`,
|
174
|
-
datePattern: 'YYYY-MM-DD-HH',
|
175
|
-
zippedArchive: false,
|
176
|
-
maxSize: '20m',
|
177
|
-
maxFiles: '14d',
|
178
|
-
level: 'info'
|
179
|
-
}),
|
180
|
-
new shell_1.PubSubLogTransport({
|
181
|
-
topic: 'connection-log'
|
182
|
-
})
|
183
|
-
]
|
184
|
-
});
|
185
193
|
//# sourceMappingURL=connection-manager.js.map
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"connection-manager.js","sourceRoot":"","sources":["../../server/engine/connection-manager.ts"],"names":[],"mappings":";;;;AAAA,8EAAoC;AACpC,qCAA0D;AAE1D,iDAAyF;AAEzF,wCAAyD;AAEzD,iEAA4D;AAE5D,MAAM,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,GAAG,gBAAM,CAAA;AACjD,MAAM,KAAK,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC,6CAA6C,CAAC,CAAA;AAE7E,SAAS,iBAAiB;IACxB,IAAI,CAAC;QACH,MAAM,QAAQ,GAAG,IAAI,CAAC,cAAc,EAAE,CAAC,eAAe,EAAE,CAAC,QAAQ,CAAA;QACjE,IAAI,CAAC,QAAQ,EAAE,CAAC;YACd,MAAM,IAAI,KAAK,CAAC,4BAA4B,CAAC,CAAA;QAC/C,CAAC;QACD,OAAO,QAAQ,CAAA;IACjB,CAAC;IAAC,OAAO,CAAC,EAAE,CAAC;QACX,OAAO,CAAC,IAAI,CAAC,qDAAqD,EAAE,CAAC,CAAC,CAAA;QACtE,OAAO,KAAK,CAAA;IACd,CAAC;AACH,CAAC;AAED,MAAM,SAAS,GAAG,iBAAiB,EAAE,CAAA;AACrC,MAAM,eAAe,GAAG,IAAA,gBAAM,EAAC,CAAC,IAAI,EAAE,IAAqB,EAAE,EAAE;IAC7D,IA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AAG,MAAM,CAAC,CAAC,EAAE,KAAK,EAAE,OAAO,EAAE,SAAS,EAAE,KAAK,EAAE,EAAE,EAAE;IACzE,OAAO,GAAG,SAAS,IAAI,KAAK,KAAK,KAAK,IAAI,OAAO,EAAE,CAAA;AACrD,CAAC,CAAC,CAAA;AAEY,wBAAM,GAAG,IAAA,sBAAY,EAAC;IAClC,MAAM,EAAE,OAAO,CAAC,MAAM,CAAC,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,EAAE,eAAe,CAAC,EAAE,EAAE,EAAE,SAAS,EAAE,CAAC,EAAE,KAAK,EAAE,EAAE,iBAAiB,CAAC,SAAS,CAAC;IAClH,UAAU,EAAE;QACV,IAAK,oBAAkB,CAAC,eAAe,CAAC;YACtC,QAAQ,EAAE,6BAA6B;YACvC,WAAW,EAAE,eAAe;YAC5B,aAAa,EAAE,KAAK;YACpB,OAAO,EAAE,KAAK;YACd,QAAQ,EAAE,KAAK;YACf,KAAK,EAAE,MAAM;SACd,CAAC;QACF,IAAI,0BAAkB,CAAC;YACrB,KAAK,EAAE,gBAAgB;SACxB,CAAC;KACH;CACF,CAAC,CAAA","sourcesContent":["import moment from 'moment-timezone'\nimport { createLogger, format, transports } from 'winston'\n\nimport { Domain, getRepository, pubsub, PubSubLogTransport } from '@things-factory/shell'\n\nimport { Connection, ConnectionStatus } from '../service'\nimport { Connector } from './types'\nimport { ProxyConnector } from './connector/proxy-connector'\n\nconst { combine, splat, printf, errors } = format\nconst debug = require('debug')('things-factory:integration-base:connections')\n\nfunction getSystemTimeZone() {\n try {\n const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone\n if (!timeZone) {\n throw new Error('Unable to resolve timeZone')\n }\n return timeZone\n } catch (e) {\n console.warn('Failed to get system timeZone, falling back to UTC.', e)\n return 'UTC'\n }\n}\n\nconst SYSTEM_TZ = getSystemTimeZone()\nconst systemTimestamp = format((info, opts: { tz?: string }) => {\n if (opts.tz) info.timestamp = moment().tz(opts.tz).format()\n return info\n})\n\nexport class ConnectionManager {\n private static connectors: { [propName: string]: Connector } = {}\n private static connections: { [domainId: string]: { [name: string]: any } } = {}\n private static entities = {}\n private static logFormat = printf(({ level, message, timestamp, stack }) => {\n return `${timestamp} ${level}: ${stack || message}`\n })\n\n public static logger = createLogger({\n format: combine(errors({ stack: true }), systemTimestamp({ tz: SYSTEM_TZ }), splat(), ConnectionManager.logFormat),\n transports: [\n new (transports as any).DailyRotateFile({\n filename: `logs/connections-%DATE%.log`,\n datePattern: 'YYYY-MM-DD-HH',\n zippedArchive: false,\n maxSize: '20m',\n maxFiles: '14d',\n level: 'info'\n }),\n new PubSubLogTransport({\n topic: 'connection-log'\n })\n ]\n })\n\n static async ready() {\n const CONNECTIONS = (\n await getRepository(Connection).find({\n where: { active: true },\n relations: ['domain', 'edge', 'creator', 'updater']\n })\n ).map(connection => {\n return {\n ...connection,\n params: connection.params || {}\n }\n })\n\n ConnectionManager.logger.info('Initializing ConnectionManager...')\n\n return await Promise.all(\n [...Object.keys(ConnectionManager.connectors), 'proxy-connector'].map(type => {\n const connector = type == 'proxy-connector' ? ProxyConnector.instance : ConnectionManager.getConnector(type)\n\n ConnectionManager.logger.info(`Connector '${type}' started to ready`)\n\n return connector\n .ready(\n CONNECTIONS.filter(connection => {\n if (type == 'proxy-connector') {\n return !!connection.edge\n } else {\n return !connection.edge && connection.type == type\n }\n }) as any\n )\n .catch(error => {\n ConnectionManager.logger.error(error)\n })\n .then(() => {\n ConnectionManager.logger.info(`All connector for '${type}' ready`)\n })\n })\n ).then(() => {\n ConnectionManager.logger.info('ConnectionManager initialization done:')\n Object.keys(ConnectionManager.connections).forEach(key => {\n var connections = ConnectionManager.connections[key]\n ConnectionManager.logger.info('For domain(%s) : %s', key, JSON.stringify(Object.keys(connections)))\n })\n })\n }\n\n static registerConnector(type: string, connector: Connector) {\n ConnectionManager.connectors[type] = connector\n }\n\n static getConnector(type: string): Connector {\n return ConnectionManager.connectors[type]\n }\n\n static getConnectors(): { [connectorName: string]: Connector } {\n return {\n ...ConnectionManager.connectors\n }\n }\n\n static unregisterConnector(type: string) {\n delete ConnectionManager.connectors[type]\n }\n\n static getConnections() {\n return ConnectionManager.connections\n }\n\n static getEntities() {\n return ConnectionManager.entities\n }\n\n static getConnectionInstance(connection: Connection): any {\n const { domain, name } = connection\n return ConnectionManager.connections[domain.id]?.[name]\n }\n\n static getConnectionInstanceByName(domain: Domain, name: string) {\n const connections = ConnectionManager.connections[domain.id]\n const connection = connections?.[name]\n\n if (!connection) {\n throw `The connection with the given name(${name}) cannot be found`\n }\n\n return connection\n }\n\n static getConnectionInstanceEntityByName(domain: Domain, name: string): any {\n const connection = ConnectionManager.entities[domain.id]?.[name]\n if (connection) {\n return connection\n }\n\n if (domain.parentId) {\n return ConnectionManager.entities[domain.id]?.[name]\n }\n }\n\n static getConnectionInstances(domain: Domain): { [connectionName: string]: any } {\n const connections = ConnectionManager.connections[domain.id]\n const parentConnections = domain.parentId && ConnectionManager.connections[domain.parentId]\n\n return {\n ...parentConnections,\n ...connections\n }\n }\n\n static getConnectionInstanceEntities(domain: Domain): { [connectionName: string]: any } {\n const connections = ConnectionManager.entities[domain.id]\n\n return {\n ...connections\n }\n }\n\n static addConnectionInstance(connection: Connection, instance: any) {\n const { domain, name } = connection\n\n var connections = ConnectionManager.connections[domain.id]\n if (!connections) {\n connections = ConnectionManager.connections[domain.id] = {}\n }\n\n var entities = ConnectionManager.entities[domain.id]\n if (!entities) {\n entities = ConnectionManager.entities[domain.id] = {}\n }\n\n connections[name] = instance\n entities[name] = connection\n\n ConnectionManager.publishState(connection, ConnectionStatus.CONNECTED)\n debug('add-connection', domain.subdomain, name)\n }\n\n static removeConnectionInstance(connection: Connection): any {\n const { domain, name } = connection\n var connections = ConnectionManager.connections[domain.id]\n var entities = ConnectionManager.entities[domain.id]\n\n var instance = connections?.[name]\n\n if (!connections || !instance) {\n debug('remove-connection', `'${name}' connection not found in domain '${domain.subdomain}'`)\n return\n }\n\n delete connections[name]\n delete entities[name]\n\n ConnectionManager.publishState(connection, ConnectionStatus.DISCONNECTED)\n debug('remove-connection', `'${name}' connection is removed from domain '${domain.subdomain}'`)\n\n return instance\n }\n\n private static async publishState(connection: Connection, state) {\n const { domain, id, name, description, type, edge } = connection\n\n pubsub.publish('connection-state', {\n connectionState: {\n domain,\n id,\n name,\n description,\n type,\n edge,\n state,\n timestamp: new Date()\n }\n })\n }\n}\n"]}
|
1
|
+
{"version":3,"file":"connection-manager.js","sourceRoot":"","sources":["../../server/engine/connection-manager.ts"],"names":[],"mappings":";;;;AAAA,8EAAoC;AACpC,qCAA0D;AAE1D,iDAAyF;AAEzF,wCAAyD;AAEzD,iEAA4D;AAE5D,MAAM,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,GAAG,gBAAM,CAAA;AACjD,MAAM,KAAK,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC,6CAA6C,CAAC,CAAA;AAE7E,SAAS,iBAAiB;IACxB,IAAI,CAAC;QACH,MAAM,QAAQ,GAAG,IAAI,CAAC,cAAc,EAAE,CAAC,eAAe,EAAE,CAAC,QAAQ,CAAA;QACjE,IAAI,CAAC,QAAQ,EAAE,CAAC;YACd,MAAM,IAAI,KAAK,CAAC,4BAA4B,CAAC,CAAA;QAC/C,CAAC;QACD,OAAO,QAAQ,CAAA;IACjB,CAAC;IAAC,OAAO,CAAC,EAAE,CAAC;QACX,OAAO,CAAC,IAAI,CAAC,qDAAqD,EAAE,CAAC,CAAC,CAAA;QACtE,OAAO,KAAK,CAAA;IACd,CAAC;AACH,CAAC;AAED,MAAM,SAAS,GAAG,iBAAiB,EAAE,CAAA;AACrC,MAAM,eAAe,GAAG,IAAA,gBAAM,EAAC,CAAC,IAAI,EAAE,IAAqB,EAAE,EAAE;IAC7D,IAAI,IAAI,CAAC,EAAE;QAAE,IAAI,CAAC,SAAS,GAAG,IAAA,yBAAM,GAAE,CAAC,EAAE,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,MAAM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B,iBAAiB,CAAC,YAAY,CAAC,UAAU,EAAE,0BAAgB,CAAC,YAAY,CAAC,CAAA;QACzE,KAAK,CAAC,mBAAmB,EAAE,IAAI,IAAI,wCAAwC,MAAM,CAAC,SAAS,GAAG,CAAC,CAAA;QAE/F,OAAO,QAAQ,CAAA;IACjB,CAAC;IAEO,MAAM,CAAC,KAAK,CAAC,YAAY,CAAC,UAAsB,EAAE,KAAK;QAC7D,MAAM,EAAE,MAAM,EAAE,EAAE,EAAE,IAAI,EAAE,WAAW,EAAE,IAAI,EAAE,IAAI,EAAE,GAAG,UAAU,CAAA;QAEhE,cAAM,CAAC,OAAO,CAAC,kBAAkB,EAAE;YACjC,eAAe,EAAE;gBACf,MAAM;gBACN,EAAE;gBACF,IAAI;gBACJ,WAAW;gBACX,IAAI;gBACJ,IAAI;gBACJ,KAAK;gBACL,SAAS,EAAE,IAAI,IAAI,EAAE;aACtB;SACF,CAAC,CAAA;IACJ,CAAC;;AAvMH,8CAwMC","sourcesContent":["import moment from 'moment-timezone'\nimport { createLogger, format, transports } from 'winston'\n\nimport { Domain, getRepository, pubsub, PubSubLogTransport } from '@things-factory/shell'\n\nimport { Connection, ConnectionStatus } from '../service'\nimport { Connector } from './types'\nimport { ProxyConnector } from './connector/proxy-connector'\n\nconst { combine, splat, printf, errors } = format\nconst debug = require('debug')('things-factory:integration-base:connections')\n\nfunction getSystemTimeZone() {\n try {\n const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone\n if (!timeZone) {\n throw new Error('Unable to resolve timeZone')\n }\n return timeZone\n } catch (e) {\n console.warn('Failed to get system timeZone, falling back to UTC.', e)\n return 'UTC'\n }\n}\n\nconst SYSTEM_TZ = getSystemTimeZone()\nconst systemTimestamp = format((info, opts: { tz?: string }) => {\n if (opts.tz) info.timestamp = moment().tz(opts.tz).format()\n return info\n})\n\nexport class ConnectionManager {\n private static connectors: { [propName: string]: Connector } = {}\n private static connections: { [domainId: string]: { [name: string]: any } } = {}\n private static entities = {}\n private static logFormat = printf(({ level, message, timestamp, stack }) => {\n return `${timestamp} ${level}: ${stack || message}`\n })\n\n public static logger = createLogger({\n format: combine(errors({ stack: true }), systemTimestamp({ tz: SYSTEM_TZ }), splat(), ConnectionManager.logFormat),\n transports: [\n new (transports as any).DailyRotateFile({\n filename: `logs/connections-%DATE%.log`,\n datePattern: 'YYYY-MM-DD-HH',\n zippedArchive: false,\n maxSize: '20m',\n maxFiles: '14d',\n level: 'info'\n }),\n new PubSubLogTransport({\n topic: 'connection-log'\n })\n ]\n })\n\n static async ready() {\n const CONNECTIONS = (\n await getRepository(Connection).find({\n where: { active: true },\n relations: ['domain', 'edge', 'creator', 'updater']\n })\n ).map(connection => {\n return {\n ...connection,\n params: connection.params || {}\n }\n })\n\n ConnectionManager.logger.info('Initializing ConnectionManager...')\n\n return await Promise.all(\n [...Object.keys(ConnectionManager.connectors), 'proxy-connector'].map(type => {\n const connector = type == 'proxy-connector' ? ProxyConnector.instance : ConnectionManager.getConnector(type)\n\n ConnectionManager.logger.info(`Connector '${type}' started to ready`)\n\n return connector\n .ready(\n CONNECTIONS.filter(connection => {\n if (type == 'proxy-connector') {\n return !!connection.edge\n } else {\n return !connection.edge && connection.type == type\n }\n }) as any\n )\n .catch(error => {\n ConnectionManager.logger.error(error)\n })\n .then(() => {\n ConnectionManager.logger.info(`All connector for '${type}' ready`)\n })\n })\n ).then(() => {\n ConnectionManager.logger.info('ConnectionManager initialization done:')\n Object.keys(ConnectionManager.connections).forEach(key => {\n var connections = ConnectionManager.connections[key]\n ConnectionManager.logger.info('For domain(%s) : %s', key, JSON.stringify(Object.keys(connections)))\n })\n })\n }\n\n static registerConnector(type: string, connector: Connector) {\n ConnectionManager.connectors[type] = connector\n }\n\n static getConnector(type: string): Connector {\n return ConnectionManager.connectors[type]\n }\n\n static getConnectors(): { [connectorName: string]: Connector } {\n return {\n ...ConnectionManager.connectors\n }\n }\n\n static unregisterConnector(type: string) {\n delete ConnectionManager.connectors[type]\n }\n\n static getConnections() {\n return ConnectionManager.connections\n }\n\n static getEntities() {\n return ConnectionManager.entities\n }\n\n static getConnectionInstance(connection: Connection): any {\n const { domain, name } = connection\n return ConnectionManager.connections[domain.id]?.[name]\n }\n\n static getConnectionInstanceByName(domain: Domain, name: string) {\n const connections = ConnectionManager.connections[domain.id]\n const connection = connections?.[name]\n\n if (!connection) {\n throw `The connection with the given name(${name}) cannot be found`\n }\n\n return connection\n }\n\n static getConnectionInstanceEntityByName(domain: Domain, name: string): any {\n const connection = ConnectionManager.entities[domain.id]?.[name]\n if (connection) {\n return connection\n }\n\n if (domain.parentId) {\n return ConnectionManager.entities[domain.id]?.[name]\n }\n }\n\n static getConnectionInstances(domain: Domain): { [connectionName: string]: any } {\n const connections = ConnectionManager.connections[domain.id]\n const parentConnections = domain.parentId && ConnectionManager.connections[domain.parentId]\n\n return {\n ...parentConnections,\n ...connections\n }\n }\n\n static getConnectionInstanceEntities(domain: Domain): { [connectionName: string]: any } {\n const connections = ConnectionManager.entities[domain.id]\n\n return {\n ...connections\n }\n }\n\n static addConnectionInstance(connection: Connection, instance: any) {\n const { domain, name } = connection\n\n var connections = ConnectionManager.connections[domain.id]\n if (!connections) {\n connections = ConnectionManager.connections[domain.id] = {}\n }\n\n var entities = ConnectionManager.entities[domain.id]\n if (!entities) {\n entities = ConnectionManager.entities[domain.id] = {}\n }\n\n connections[name] = instance\n entities[name] = connection\n\n ConnectionManager.publishState(connection, ConnectionStatus.CONNECTED)\n debug('add-connection', domain.subdomain, name)\n }\n\n static removeConnectionInstance(connection: Connection): any {\n const { domain, name } = connection\n var connections = ConnectionManager.connections[domain.id]\n var entities = ConnectionManager.entities[domain.id]\n\n var instance = connections?.[name]\n\n if (!connections || !instance) {\n debug('remove-connection', `'${name}' connection not found in domain '${domain.subdomain}'`)\n return\n }\n\n delete connections[name]\n delete entities[name]\n\n ConnectionManager.publishState(connection, ConnectionStatus.DISCONNECTED)\n debug('remove-connection', `'${name}' connection is removed from domain '${domain.subdomain}'`)\n\n return instance\n }\n\n private static async publishState(connection: Connection, state) {\n const { domain, id, name, description, type, edge } = connection\n\n pubsub.publish('connection-state', {\n connectionState: {\n domain,\n id,\n name,\n description,\n type,\n edge,\n state,\n timestamp: new Date()\n }\n })\n }\n}\n"]}
|
@@ -40,7 +40,10 @@ class GraphqlConnector {
|
|
40
40
|
const authMiddleware = new core_1.ApolloLink((operation, forward) => {
|
41
41
|
// add the authorization to the headers
|
42
42
|
operation.setContext(({ headers = {} }) => ({
|
43
|
-
headers:
|
43
|
+
headers: {
|
44
|
+
...headers,
|
45
|
+
...oauth2Client.getAuthHeaders()
|
46
|
+
}
|
44
47
|
}));
|
45
48
|
return forward(operation);
|
46
49
|
});
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"graphql-connector.js","sourceRoot":"","sources":["../../../server/engine/connector/graphql-connector.ts"],"names":[],"mappings":";;;AAAA,gCAA6B;AAE7B,8CAA6F;AAC7F,qDAAmD;AACnD,iEAA4D;AAC5D,iDAAqD;AAErD,8DAAyD;AAIzD,MAAM,cAAc,GAAQ;IAC1B,UAAU,EAAE;QACV,WAAW,EAAE,UAAU;QACvB,WAAW,EAAE,QAAQ;KACtB;IACD,KAAK,EAAE;QACL,WAAW,EAAE,UAAU,EAAE,gBAAgB;QACzC,WAAW,EAAE,KAAK;KACnB;IACD,MAAM,EAAE;QACN,WAAW,EAAE,KAAK;KACnB;CACF,CAAA;AAED,MAAa,gBAAgB;IAC3B,KAAK,CAAC,KAAK,CAAC,iBAAoC;QAC9C,MAAM,OAAO,CAAC,GAAG,CAAC,iBAAiB,CAAC,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAA;QAEjE,sCAAiB,CAAC,MAAM,CAAC,IAAI,CAAC,yCAAyC,CAAC,CAAA;IAC1E,CAAC;IAED,KAAK,CAAC,OAAO,CAAC,UAA2B;QACvC,MAAM,EACJ,QAAQ,EAAE,GAAG,EACb,MAAM,EAAE,E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AAW;QACb,OAAO,wBAAwB,CAAA;IACjC,CAAC;IAED,IAAI,IAAI;QACN,OAAO,yCAAyC,CAAA;IAClD,CAAC;CACF;AAlGD,4CAkGC;AAED,sCAAiB,CAAC,iBAAiB,CAAC,mBAAmB,EAAE,IAAI,gBAAgB,EAAE,CAAC,CAAA","sourcesContent":["import 'cross-fetch/polyfill'\n\nimport { ApolloClient, ApolloLink, from, HttpLink, InMemoryCache } from '@apollo/client/core'\nimport { onError } from '@apollo/client/link/error'\nimport { Oauth2Client } from '@things-factory/oauth2-client'\nimport { getRepository } from '@things-factory/shell'\n\nimport { ConnectionManager } from '../connection-manager'\nimport { Connector } from '../types'\nimport { InputConnection } from '../../service/connection/connection-type'\n\nconst defaultOptions: any = {\n watchQuery: {\n fetchPolicy: 'no-cache',\n errorPolicy: 'ignore'\n },\n query: {\n fetchPolicy: 'no-cache', //'network-only'\n errorPolicy: 'all'\n },\n mutate: {\n errorPolicy: 'all'\n }\n}\n\nexport class GraphqlConnector implements Connector {\n async ready(connectionConfigs: InputConnection[]) {\n await Promise.all(connectionConfigs.map(this.connect.bind(this)))\n\n ConnectionManager.logger.info('graphql-connector connections are ready')\n }\n\n async connect(connection: InputConnection) {\n const {\n endpoint: uri,\n params: { authClient }\n } = connection\n\n const ERROR_HANDLER: any = ({ graphQLErrors, networkError }) => {\n if (graphQLErrors)\n graphQLErrors.map(({ message, locations, path }) => {\n ConnectionManager.logger.error(\n `[GraphQL error] Message: ${message}, Location: ${locations}, Path: ${path}`,\n graphQLErrors\n )\n })\n\n if (networkError) {\n ConnectionManager.logger.error(`[Network error - ${networkError.statusCode}]`, networkError)\n }\n }\n\n const oauth2Client: Oauth2Client = await getRepository(Oauth2Client).findOneBy({ id: authClient })\n\n const authMiddleware = new ApolloLink((operation, forward) => {\n // add the authorization to the headers\n operation.setContext(({ headers = {} }) => ({\n headers: {\n ...headers,\n ...oauth2Client.getAuthHeaders()\n }\n }))\n\n return forward(operation)\n })\n\n const cache = new InMemoryCache({\n addTypename: false\n })\n\n ConnectionManager.addConnectionInstance(\n connection,\n new ApolloClient({\n defaultOptions,\n cache,\n link: from([\n authMiddleware,\n onError(ERROR_HANDLER),\n new HttpLink({\n uri,\n credentials: 'include'\n })\n ])\n })\n )\n\n ConnectionManager.logger.info(\n `graphql-connector connection(${connection.name}:${connection.endpoint}) is connected`\n )\n }\n\n async disconnect(connection: InputConnection) {\n const client = ConnectionManager.getConnectionInstance(connection)\n client.stop()\n ConnectionManager.removeConnectionInstance(connection)\n\n ConnectionManager.logger.info(`graphql-connector connection(${connection.name}) is disconnected`)\n }\n\n get parameterSpec() {\n return [\n {\n type: 'entity-selector',\n name: 'authClient',\n label: 'auth-client',\n property: {\n queryName: 'oauth2Clients'\n }\n }\n ]\n }\n\n get taskPrefixes() {\n return ['graphql']\n }\n\n get description() {\n return 'Graphql Http Connector'\n }\n\n get help() {\n return 'integration/connector/graphql-connector'\n }\n}\n\nConnectionManager.registerConnector('graphql-connector', new GraphqlConnector())\n"]}
|
@@ -118,12 +118,11 @@ class HeadlessConnector {
|
|
118
118
|
}
|
119
119
|
});
|
120
120
|
page.on('requestfailed', request => {
|
121
|
-
var _a;
|
122
121
|
try {
|
123
122
|
console.log('Request failed:');
|
124
123
|
console.log(`- URL: ${request.url()}`);
|
125
124
|
console.log(`- Method: ${request.method()}`);
|
126
|
-
console.log(`- Failure Text: ${
|
125
|
+
console.log(`- Failure Text: ${request.failure()?.errorText}`);
|
127
126
|
console.log(`- Headers:`, request.headers());
|
128
127
|
// POST 데이터 (필요한 경우)
|
129
128
|
if (request.postData()) {
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"headless-connector.js","sourceRoot":"","sources":["../../../server/engine/connector/headless-connector.ts"],"names":[],"mappings":";;;AAAA,8DAAyD;AAEzD,kEAAgE;AAGhE;;;;;;;;;;EAUE;AAEF,MAAa,iBAAiB;IAC5B,KAAK,CAAC,KAAK,CAAC,iBAAiB;QAC3B,MAAM,OAAO,CAAC,GAAG,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GAAG,GAAG,CAAC,CAAA;AACvE,CAAC","sourcesContent":["import { ConnectionManager } from '../connection-manager'\nimport { Connector } from '../types'\nimport { getHeadlessPool } from '../resource-pool/headless-pool'\nimport { Browser, Page } from 'puppeteer'\n\n/*\n Functionality of the headless-connector:\n - Provides a mechanism to acquire an active session page.\n - Performs login when necessary to obtain valid cookies.\n - Applies these cookies to the page for session management.\n - Pages are acquired from the `headlessPool`, which manages browser instances.\n - During the login process, pages from the pool are used for actions like form filling and navigation.\n - Valid cookies are saved after login and reused for subsequent page acquisitions.\n - Users must explicitly release the page after use through the `releasePage` method.\n - Released pages are returned to the `headlessPool` for reuse.\n*/\n\nexport class HeadlessConnector implements Connector {\n async ready(connectionConfigs) {\n await Promise.all(connectionConfigs.map(this.connect.bind(this)))\n ConnectionManager.logger.info('headless-connector connections are ready')\n }\n\n async connect(connection) {\n const {\n endpoint: uri = '1',\n params: {\n username = '',\n password = '',\n loginPagePath = '/login',\n loginApiUrl = null,\n usernameSelector = '#username',\n passwordSelector = '#password',\n submitSelector = '#submit',\n successSelector = null,\n shadowDomSelectors = '', // Comma separated shadow DOM selectors\n timeout = 15000, // Default timeout for operations\n retries = 3 // Default number of retries for login or page actions\n } = {}\n } = connection\n\n const loginInfo = {\n loginRequired: Boolean(username), // Determine if login is required\n username,\n password,\n loginPagePath,\n loginApiUrl,\n timeout,\n retries,\n loginSelectors: {\n usernameSelector,\n passwordSelector,\n submitSelector,\n successSelector,\n shadowDomSelectors: shadowDomSelectors\n .split(',')\n .map(selector => selector.trim())\n .filter(Boolean)\n }\n }\n\n async function acquireBrowser() {\n try {\n const pool = getHeadlessPool()\n const browser = await pool.acquire()\n return browser\n } catch (error) {\n ConnectionManager.logger.error('Failed to acquire browser:', error)\n throw error\n }\n }\n\n async function releaseBrowser(browser: Browser) {\n try {\n const pool = getHeadlessPool()\n await pool.release(browser)\n } catch (error) {\n ConnectionManager.logger.error('Failed to release browser:', error)\n }\n }\n\n ConnectionManager.addConnectionInstance(connection, {\n endpoint: connection.endpoint,\n params: connection.params,\n acquireSessionPage: async () => {\n const browser = await acquireBrowser()\n let page\n let cookies = connection.cookies\n\n try {\n page = await browser.newPage()\n\n await page.setRequestInterception(true)\n\n await page.setBypassCSP(true)\n\n await page.setUserAgent(\n 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.6778.204 Safari/537.36'\n )\n\n await page.evaluateOnNewDocument(() => {\n Object.defineProperty(navigator, 'webdriver', { get: () => false })\n })\n\n await page.setExtraHTTPHeaders({\n 'Upgrade-Insecure-Requests': '0',\n 'accept-language': 'en-US,en;q=0.9',\n // 'upgrade-insecure-requests': '0',\n referer: uri\n })\n\n await page.setDefaultNavigationTimeout(timeout)\n\n page.on('console', async msg => {\n ConnectionManager.logger.info(`[browser ${msg.type()}] ${msg.text()}`)\n })\n\n page.on('request', request => {\n if (request.isInterceptResolutionHandled()) {\n return\n }\n\n const resourceType = request.resourceType()\n\n const headers = request.headers()\n if (headers['access-control-request-headers']) {\n const filteredHeaders = headers['access-control-request-headers']\n .split(',')\n .map(header => header.trim())\n .filter(header => header.toLowerCase() !== 'upgrade-insecure-requests') // 해당 헤더 제거\n\n if (filteredHeaders.length > 0) {\n headers['access-control-request-headers'] = filteredHeaders.join(', ')\n } else {\n delete headers['access-control-request-headers'] // 필요하면 전체 삭제\n }\n }\n\n // 일반적인 요청에서도 'upgrade-insecure-requests' 헤더 제거\n if (headers['upgrade-insecure-requests']) {\n delete headers['upgrade-insecure-requests']\n }\n\n if (['image', 'stylesheet', 'font'].includes(resourceType)) {\n request.abort() // 비필수 리소스 요청 차단\n } else {\n request.continue() // 나머지 요청은 진행\n }\n })\n\n page.on('requestfailed', request => {\n try {\n console.log('Request failed:')\n console.log(`- URL: ${request.url()}`)\n console.log(`- Method: ${request.method()}`)\n console.log(`- Failure Text: ${request.failure()?.errorText}`)\n console.log(`- Headers:`, request.headers())\n\n // POST 데이터 (필요한 경우)\n if (request.postData()) {\n console.log(`- Post Data: ${request.postData()}`)\n }\n } catch (error) {\n console.error('Error in requestfailed handler:', error)\n }\n })\n\n if (loginInfo.loginRequired) {\n // 현재 세션의 Authorization 헤더 확인\n const headers = await page.evaluate(() => {\n return fetch(window.location.href, { method: 'GET' })\n .then(response => response.headers.get('Authorization'))\n .catch(() => null)\n })\n\n if (headers) {\n ConnectionManager.logger.info('User is already logged in, skipping login process.')\n return page\n }\n\n if (cookies && isCookieValid(cookies)) {\n await this.applyCookiesAndVerifySession(page, cookies, loginInfo)\n return page\n }\n\n await this.performLogin(page, uri, loginInfo)\n cookies = await page.cookies()\n connection.cookies = cookies\n }\n\n return page\n } catch (error) {\n ConnectionManager.logger.error('Failed to acquire session page:', error)\n throw error\n }\n },\n releasePage: async (page: Page) => {\n try {\n if (page) {\n const browser = page.browser()\n await page.close()\n await releaseBrowser(browser)\n }\n } catch (error) {\n ConnectionManager.logger.error('Failed to release page:', error)\n }\n },\n acquireBrowser,\n releaseBrowser\n })\n\n ConnectionManager.logger.info(\n `headless-connector connection(${connection.name}:${connection.endpoint}) is connected`\n )\n }\n\n async applyCookiesAndVerifySession(page, cookies, loginInfo) {\n await page.setCookie(...cookies)\n await page.reload({ waitUntil: 'networkidle2', timeout: loginInfo.timeout })\n\n if (loginInfo.loginRequired && loginInfo.loginSelectors.successSelector) {\n const success = await this.resolveShadowDom(\n page,\n loginInfo.loginSelectors.shadowDomSelectors,\n loginInfo.loginSelectors.successSelector\n )\n if (!success) {\n throw new Error('Session invalid, login required')\n }\n }\n }\n\n async performLogin(page, uri, loginInfo) {\n for (let attempt = 1; attempt <= loginInfo.retries; attempt++) {\n try {\n await page.goto(`${uri}${loginInfo.loginPagePath}`, { waitUntil: 'networkidle2', timeout: loginInfo.timeout })\n\n const usernameInput = await this.resolveShadowDom(\n page,\n loginInfo.loginSelectors.shadowDomSelectors,\n loginInfo.loginSelectors.usernameSelector\n )\n const passwordInput = await this.resolveShadowDom(\n page,\n loginInfo.loginSelectors.shadowDomSelectors,\n loginInfo.loginSelectors.passwordSelector\n )\n const submitButton = await this.resolveShadowDom(\n page,\n loginInfo.loginSelectors.shadowDomSelectors,\n loginInfo.loginSelectors.submitSelector\n )\n\n if (!usernameInput || !passwordInput || !submitButton) {\n throw new Error('Failed to locate input elements in shadow DOM')\n }\n\n await usernameInput.type(loginInfo.username)\n await passwordInput.type(loginInfo.password)\n\n var loginApiUrl =\n loginInfo.loginApiUrl ||\n (await page.evaluate(button => {\n const form = button.closest('form')\n return form ? form.action : null\n }, submitButton))\n\n if (loginApiUrl && !loginApiUrl.startsWith('http')) {\n loginApiUrl = `${uri}${loginApiUrl}`\n }\n\n if (!loginApiUrl) {\n throw new Error('❌ Unable to detect login API URL!')\n }\n\n console.log('✅ Detected login API URL:', loginApiUrl)\n\n const [response] = await Promise.all([\n page.waitForResponse(response => {\n const url = response.url()\n const method = response.request().method()\n\n return url === loginApiUrl && method === 'POST' && [200, 201, 204, 302, 304].includes(response.status())\n }),\n page.evaluate(button => button.click(), submitButton),\n page.waitForNavigation({ waitUntil: 'networkidle2', timeout: loginInfo.timeout }) // 로그인 후 리디렉션 감지\n ])\n\n if (response) {\n const status = response.status()\n if (status >= 200 && status < 400) {\n ConnectionManager.logger.info(`Login successful with status code: ${status}`)\n return\n } else if (status >= 400) {\n throw new Error(`Login failed with status code: ${status}`)\n }\n } else {\n throw new Error('No response received during login')\n }\n\n if (loginInfo.loginSelectors.successSelector) {\n const success = await this.resolveShadowDom(\n page,\n loginInfo.loginSelectors.shadowDomSelectors,\n loginInfo.loginSelectors.successSelector\n )\n if (!success) {\n throw new Error('Login failed: Success selector not found')\n }\n }\n } catch (error) {\n ConnectionManager.logger.warn(`Login attempt ${attempt} failed:`, error)\n\n try {\n await page.screenshot({ path: `logs/login-failure-attempt-${attempt}.png` })\n } catch (error) {\n ConnectionManager.logger.error('Failed to capture screenshot:', error)\n }\n\n if (attempt === loginInfo.retries) {\n throw new Error(`Login failed after ${loginInfo.retries} attempts`)\n }\n }\n }\n }\n\n async resolveShadowDom(page, shadowSelectors, targetSelector) {\n let context\n\n if (!shadowSelectors || shadowSelectors.length === 0) {\n // No Shadow DOM path; use document root as the context\n context = page.mainFrame() // Puppeteer uses frames to represent document\n return context.$(targetSelector) // Search directly in the document root\n }\n\n context = page // Start with the page as the context\n for (const selector of shadowSelectors) {\n const shadowHost = await context.$(selector)\n if (!shadowHost) {\n throw new Error(`Shadow host not found: ${selector}`)\n }\n context = await page.evaluateHandle(host => host.shadowRoot, shadowHost)\n }\n return context.evaluateHandle((shadowRoot, selector) => shadowRoot.querySelector(selector), targetSelector)\n }\n\n async disconnect(connection) {\n ConnectionManager.removeConnectionInstance(connection)\n ConnectionManager.logger.info(`headless-connector connection(${connection.name}) is disconnected`)\n }\n\n get parameterSpec() {\n return [\n {\n type: 'string',\n name: 'username',\n label: 'username'\n },\n {\n type: 'password',\n name: 'password',\n label: 'password'\n },\n {\n type: 'string',\n name: 'loginPagePath',\n label: 'login-page-path'\n },\n {\n type: 'string',\n name: 'loginApiUrl',\n label: 'login-api-url'\n },\n {\n type: 'string',\n name: 'usernameSelector',\n label: 'username-selector'\n },\n {\n type: 'string',\n name: 'passwordSelector',\n label: 'password-selector'\n },\n {\n type: 'string',\n name: 'submitSelector',\n label: 'submit-selector'\n },\n {\n type: 'string',\n name: 'successSelector',\n label: 'success-selector'\n },\n {\n type: 'string',\n name: 'shadowDomSelectors',\n label: 'shadow-dom-selectors'\n },\n {\n type: 'number',\n name: 'timeout',\n label: 'timeout',\n value: 15000\n },\n {\n type: 'number',\n name: 'retries',\n label: 'maximum-retries',\n value: 3\n }\n ]\n }\n\n get taskPrefixes() {\n return ['headless']\n }\n\n get description() {\n return 'Headless Pool Connector with login capabilities'\n }\n\n get help() {\n return 'integration/connector/headless-connector'\n }\n}\n\nConnectionManager.registerConnector('headless-connector', new HeadlessConnector())\n\nfunction isCookieValid(cookies) {\n if (!cookies || cookies.length === 0) return false\n const now = Date.now() / 1000 // Current time in seconds\n return cookies.some(cookie => cookie.expires && cookie.expires > now)\n}\n"]}
|
1
|
+
{"version":3,"file":"headless-connector.js","sourceRoot":"","sources":["../../../server/engine/connector/headless-connector.ts"],"names":[],"mappings":";;;AAAA,8DAAyD;AAEzD,kEAAgE;AAGhE;;;;;;;;;;EAUE;AAEF,MAAa,iBAAiB;IAC5B,KAAK,CAAC,KAAK,CAAC,iBAAiB;QAC3B,MAAM,OAAO,CAAC,GAAG,CAAC,iBAAiB,CAAC,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAA;QACjE,sCAAiB,CAAC,MAAM,CAAC,IAAI,CAAC,0CAA0C,CAAC,CAAA;IAC3E,CAAC;IAED,KAAK,CAAC,OAAO,CAAC,UAAU;QACtB,MAAM,EACJ,QAAQ,EAAE,GAAG,GAAG,GAAG,EACnB,MAAM,EAAE,EACN,QAAQ,GAAG,EAAE,EACb,QAAQ,GAAG,EAAE,EACb,aAAa,GAAG,QAAQ,EACxB,WAAW,GAAG,IAAI,EAClB,gBAAgB,GAAG,WAAW,EAC9B,gBAAgB,GAAG,WAAW,EAC9B,cAAc,GAAG,SAAS,EAC1B,eAAe,GAAG,IAAI,EACtB,kBAAkB,GAAG,EAAE,EAAE,uCAAuC;QAChE,OAAO,GAAG,KAAK,EAAE,iCAAiC;QAClD,OAAO,GAAG,CAAC,CAAC,sDAAsD;UACnE,GAAG,EAAE,EACP,GAAG,UAAU,CAAA;QAEd,MAAM,SAAS,GAAG;YAChB,aAAa,EAAE,OAAO,CAAC,QAAQ,CAAC,EAAE,iCAAiC;YACnE,QAAQ;YACR,QAAQ;YACR,aAAa;YACb,WAAW;YACX,OAAO;YACP,OAAO;YACP,cAAc,EAAE;gBACd,gBAAgB;gBAChB,gBAAgB;gBAChB,cAAc;gBACd,eAAe;gBACf,kBAAkB,EAAE,kBAAkB;qBACnC,KAAK,CAAC,GAAG,CAAC;qBACV,GAAG,CAAC,QAAQ,CAAC,EA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IAC5B,IAAI,CAAC,OAAO,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,KAAK,CAAA;IAClD,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,CAAA,CAAC,0BAA0B;IACxD,OAAO,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,EAAE,CAAC,MAAM,CAAC,OAAO,IAAI,MAAM,CAAC,OAAO,GAAG,GAAG,CAAC,CAAA;AACvE,CAAC","sourcesContent":["import { ConnectionManager } from '../connection-manager'\nimport { Connector } from '../types'\nimport { getHeadlessPool } from '../resource-pool/headless-pool'\nimport { Browser, Page } from 'puppeteer'\n\n/*\n Functionality of the headless-connector:\n - Provides a mechanism to acquire an active session page.\n - Performs login when necessary to obtain valid cookies.\n - Applies these cookies to the page for session management.\n - Pages are acquired from the `headlessPool`, which manages browser instances.\n - During the login process, pages from the pool are used for actions like form filling and navigation.\n - Valid cookies are saved after login and reused for subsequent page acquisitions.\n - Users must explicitly release the page after use through the `releasePage` method.\n - Released pages are returned to the `headlessPool` for reuse.\n*/\n\nexport class HeadlessConnector implements Connector {\n async ready(connectionConfigs) {\n await Promise.all(connectionConfigs.map(this.connect.bind(this)))\n ConnectionManager.logger.info('headless-connector connections are ready')\n }\n\n async connect(connection) {\n const {\n endpoint: uri = '1',\n params: {\n username = '',\n password = '',\n loginPagePath = '/login',\n loginApiUrl = null,\n usernameSelector = '#username',\n passwordSelector = '#password',\n submitSelector = '#submit',\n successSelector = null,\n shadowDomSelectors = '', // Comma separated shadow DOM selectors\n timeout = 15000, // Default timeout for operations\n retries = 3 // Default number of retries for login or page actions\n } = {}\n } = connection\n\n const loginInfo = {\n loginRequired: Boolean(username), // Determine if login is required\n username,\n password,\n loginPagePath,\n loginApiUrl,\n timeout,\n retries,\n loginSelectors: {\n usernameSelector,\n passwordSelector,\n submitSelector,\n successSelector,\n shadowDomSelectors: shadowDomSelectors\n .split(',')\n .map(selector => selector.trim())\n .filter(Boolean)\n }\n }\n\n async function acquireBrowser() {\n try {\n const pool = getHeadlessPool()\n const browser = await pool.acquire()\n return browser\n } catch (error) {\n ConnectionManager.logger.error('Failed to acquire browser:', error)\n throw error\n }\n }\n\n async function releaseBrowser(browser: Browser) {\n try {\n const pool = getHeadlessPool()\n await pool.release(browser)\n } catch (error) {\n ConnectionManager.logger.error('Failed to release browser:', error)\n }\n }\n\n ConnectionManager.addConnectionInstance(connection, {\n endpoint: connection.endpoint,\n params: connection.params,\n acquireSessionPage: async () => {\n const browser = await acquireBrowser()\n let page\n let cookies = connection.cookies\n\n try {\n page = await browser.newPage()\n\n await page.setRequestInterception(true)\n\n await page.setBypassCSP(true)\n\n await page.setUserAgent(\n 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.6778.204 Safari/537.36'\n )\n\n await page.evaluateOnNewDocument(() => {\n Object.defineProperty(navigator, 'webdriver', { get: () => false })\n })\n\n await page.setExtraHTTPHeaders({\n 'Upgrade-Insecure-Requests': '0',\n 'accept-language': 'en-US,en;q=0.9',\n // 'upgrade-insecure-requests': '0',\n referer: uri\n })\n\n await page.setDefaultNavigationTimeout(timeout)\n\n page.on('console', async msg => {\n ConnectionManager.logger.info(`[browser ${msg.type()}] ${msg.text()}`)\n })\n\n page.on('request', request => {\n if (request.isInterceptResolutionHandled()) {\n return\n }\n\n const resourceType = request.resourceType()\n\n const headers = request.headers()\n if (headers['access-control-request-headers']) {\n const filteredHeaders = headers['access-control-request-headers']\n .split(',')\n .map(header => header.trim())\n .filter(header => header.toLowerCase() !== 'upgrade-insecure-requests') // 해당 헤더 제거\n\n if (filteredHeaders.length > 0) {\n headers['access-control-request-headers'] = filteredHeaders.join(', ')\n } else {\n delete headers['access-control-request-headers'] // 필요하면 전체 삭제\n }\n }\n\n // 일반적인 요청에서도 'upgrade-insecure-requests' 헤더 제거\n if (headers['upgrade-insecure-requests']) {\n delete headers['upgrade-insecure-requests']\n }\n\n if (['image', 'stylesheet', 'font'].includes(resourceType)) {\n request.abort() // 비필수 리소스 요청 차단\n } else {\n request.continue() // 나머지 요청은 진행\n }\n })\n\n page.on('requestfailed', request => {\n try {\n console.log('Request failed:')\n console.log(`- URL: ${request.url()}`)\n console.log(`- Method: ${request.method()}`)\n console.log(`- Failure Text: ${request.failure()?.errorText}`)\n console.log(`- Headers:`, request.headers())\n\n // POST 데이터 (필요한 경우)\n if (request.postData()) {\n console.log(`- Post Data: ${request.postData()}`)\n }\n } catch (error) {\n console.error('Error in requestfailed handler:', error)\n }\n })\n\n if (loginInfo.loginRequired) {\n // 현재 세션의 Authorization 헤더 확인\n const headers = await page.evaluate(() => {\n return fetch(window.location.href, { method: 'GET' })\n .then(response => response.headers.get('Authorization'))\n .catch(() => null)\n })\n\n if (headers) {\n ConnectionManager.logger.info('User is already logged in, skipping login process.')\n return page\n }\n\n if (cookies && isCookieValid(cookies)) {\n await this.applyCookiesAndVerifySession(page, cookies, loginInfo)\n return page\n }\n\n await this.performLogin(page, uri, loginInfo)\n cookies = await page.cookies()\n connection.cookies = cookies\n }\n\n return page\n } catch (error) {\n ConnectionManager.logger.error('Failed to acquire session page:', error)\n throw error\n }\n },\n releasePage: async (page: Page) => {\n try {\n if (page) {\n const browser = page.browser()\n await page.close()\n await releaseBrowser(browser)\n }\n } catch (error) {\n ConnectionManager.logger.error('Failed to release page:', error)\n }\n },\n acquireBrowser,\n releaseBrowser\n })\n\n ConnectionManager.logger.info(\n `headless-connector connection(${connection.name}:${connection.endpoint}) is connected`\n )\n }\n\n async applyCookiesAndVerifySession(page, cookies, loginInfo) {\n await page.setCookie(...cookies)\n await page.reload({ waitUntil: 'networkidle2', timeout: loginInfo.timeout })\n\n if (loginInfo.loginRequired && loginInfo.loginSelectors.successSelector) {\n const success = await this.resolveShadowDom(\n page,\n loginInfo.loginSelectors.shadowDomSelectors,\n loginInfo.loginSelectors.successSelector\n )\n if (!success) {\n throw new Error('Session invalid, login required')\n }\n }\n }\n\n async performLogin(page, uri, loginInfo) {\n for (let attempt = 1; attempt <= loginInfo.retries; attempt++) {\n try {\n await page.goto(`${uri}${loginInfo.loginPagePath}`, { waitUntil: 'networkidle2', timeout: loginInfo.timeout })\n\n const usernameInput = await this.resolveShadowDom(\n page,\n loginInfo.loginSelectors.shadowDomSelectors,\n loginInfo.loginSelectors.usernameSelector\n )\n const passwordInput = await this.resolveShadowDom(\n page,\n loginInfo.loginSelectors.shadowDomSelectors,\n loginInfo.loginSelectors.passwordSelector\n )\n const submitButton = await this.resolveShadowDom(\n page,\n loginInfo.loginSelectors.shadowDomSelectors,\n loginInfo.loginSelectors.submitSelector\n )\n\n if (!usernameInput || !passwordInput || !submitButton) {\n throw new Error('Failed to locate input elements in shadow DOM')\n }\n\n await usernameInput.type(loginInfo.username)\n await passwordInput.type(loginInfo.password)\n\n var loginApiUrl =\n loginInfo.loginApiUrl ||\n (await page.evaluate(button => {\n const form = button.closest('form')\n return form ? form.action : null\n }, submitButton))\n\n if (loginApiUrl && !loginApiUrl.startsWith('http')) {\n loginApiUrl = `${uri}${loginApiUrl}`\n }\n\n if (!loginApiUrl) {\n throw new Error('❌ Unable to detect login API URL!')\n }\n\n console.log('✅ Detected login API URL:', loginApiUrl)\n\n const [response] = await Promise.all([\n page.waitForResponse(response => {\n const url = response.url()\n const method = response.request().method()\n\n return url === loginApiUrl && method === 'POST' && [200, 201, 204, 302, 304].includes(response.status())\n }),\n page.evaluate(button => button.click(), submitButton),\n page.waitForNavigation({ waitUntil: 'networkidle2', timeout: loginInfo.timeout }) // 로그인 후 리디렉션 감지\n ])\n\n if (response) {\n const status = response.status()\n if (status >= 200 && status < 400) {\n ConnectionManager.logger.info(`Login successful with status code: ${status}`)\n return\n } else if (status >= 400) {\n throw new Error(`Login failed with status code: ${status}`)\n }\n } else {\n throw new Error('No response received during login')\n }\n\n if (loginInfo.loginSelectors.successSelector) {\n const success = await this.resolveShadowDom(\n page,\n loginInfo.loginSelectors.shadowDomSelectors,\n loginInfo.loginSelectors.successSelector\n )\n if (!success) {\n throw new Error('Login failed: Success selector not found')\n }\n }\n } catch (error) {\n ConnectionManager.logger.warn(`Login attempt ${attempt} failed:`, error)\n\n try {\n await page.screenshot({ path: `logs/login-failure-attempt-${attempt}.png` })\n } catch (error) {\n ConnectionManager.logger.error('Failed to capture screenshot:', error)\n }\n\n if (attempt === loginInfo.retries) {\n throw new Error(`Login failed after ${loginInfo.retries} attempts`)\n }\n }\n }\n }\n\n async resolveShadowDom(page, shadowSelectors, targetSelector) {\n let context\n\n if (!shadowSelectors || shadowSelectors.length === 0) {\n // No Shadow DOM path; use document root as the context\n context = page.mainFrame() // Puppeteer uses frames to represent document\n return context.$(targetSelector) // Search directly in the document root\n }\n\n context = page // Start with the page as the context\n for (const selector of shadowSelectors) {\n const shadowHost = await context.$(selector)\n if (!shadowHost) {\n throw new Error(`Shadow host not found: ${selector}`)\n }\n context = await page.evaluateHandle(host => host.shadowRoot, shadowHost)\n }\n return context.evaluateHandle((shadowRoot, selector) => shadowRoot.querySelector(selector), targetSelector)\n }\n\n async disconnect(connection) {\n ConnectionManager.removeConnectionInstance(connection)\n ConnectionManager.logger.info(`headless-connector connection(${connection.name}) is disconnected`)\n }\n\n get parameterSpec() {\n return [\n {\n type: 'string',\n name: 'username',\n label: 'username'\n },\n {\n type: 'password',\n name: 'password',\n label: 'password'\n },\n {\n type: 'string',\n name: 'loginPagePath',\n label: 'login-page-path'\n },\n {\n type: 'string',\n name: 'loginApiUrl',\n label: 'login-api-url'\n },\n {\n type: 'string',\n name: 'usernameSelector',\n label: 'username-selector'\n },\n {\n type: 'string',\n name: 'passwordSelector',\n label: 'password-selector'\n },\n {\n type: 'string',\n name: 'submitSelector',\n label: 'submit-selector'\n },\n {\n type: 'string',\n name: 'successSelector',\n label: 'success-selector'\n },\n {\n type: 'string',\n name: 'shadowDomSelectors',\n label: 'shadow-dom-selectors'\n },\n {\n type: 'number',\n name: 'timeout',\n label: 'timeout',\n value: 15000\n },\n {\n type: 'number',\n name: 'retries',\n label: 'maximum-retries',\n value: 3\n }\n ]\n }\n\n get taskPrefixes() {\n return ['headless']\n }\n\n get description() {\n return 'Headless Pool Connector with login capabilities'\n }\n\n get help() {\n return 'integration/connector/headless-connector'\n }\n}\n\nConnectionManager.registerConnector('headless-connector', new HeadlessConnector())\n\nfunction isCookieValid(cookies) {\n if (!cookies || cookies.length === 0) return false\n const now = Date.now() / 1000 // Current time in seconds\n return cookies.some(cookie => cookie.expires && cookie.expires > now)\n}\n"]}
|
@@ -16,7 +16,11 @@ class HttpConnector {
|
|
16
16
|
const oauth2Client = await (0, shell_1.getRepository)(oauth2_client_1.Oauth2Client).findOneBy({ id: params.authClient });
|
17
17
|
var authHeaders = oauth2Client.getAuthHeaders();
|
18
18
|
}
|
19
|
-
connection_manager_1.ConnectionManager.addConnectionInstance(connection,
|
19
|
+
connection_manager_1.ConnectionManager.addConnectionInstance(connection, {
|
20
|
+
...connection,
|
21
|
+
authHeaders: authHeaders || {},
|
22
|
+
params
|
23
|
+
});
|
20
24
|
connection_manager_1.ConnectionManager.logger.info(`http-connector connection(${connection.name}:${connection.endpoint}) is connected`);
|
21
25
|
}
|
22
26
|
async disconnect(connection) {
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"http-connector.js","sourceRoot":"","sources":["../../../server/engine/connector/http-connector.ts"],"names":[],"mappings":";;;AAAA,iEAA4D;AAC5D,iDAAqD;AAErD,8DAAyD;AAIzD,MAAa,aAAa;IACxB,KAAK,CAAC,KAAK,CAAC,iBAAoC;QAC9C,MAAM,OAAO,CAAC,GAAG,CAAC,iBAAiB,CAAC,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAA;QAEjE,sCAAiB,CAAC,MAAM,CAAC,IAAI,CAAC,sCAAsC,CAAC,CAAA;IACvE,CAAC;IAED,KAAK,CAAC,OAAO,CAAC,UAA2B;QACvC,IAAI,EAAE,MAAM,EAAE,GAAG,UAAU,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AAqB,CAAC,UAAU,EAAE;YAClD,GAAG,UAAU;YACb,WAAW,EAAE,WAAW,IAAI,EAAE;YAC9B,MAAM;SACP,CAAC,CAAA;QAEF,sCAAiB,CAAC,MAAM,CAAC,IAAI,CAAC,6BAA6B,UAAU,CAAC,IAAI,IAAI,UAAU,CAAC,QAAQ,gBAAgB,CAAC,CAAA;IACpH,CAAC;IAED,KAAK,CAAC,UAAU,CAAC,UAA2B;QAC1C,sCAAiB,CAAC,wBAAwB,CAAC,UAAU,CAAC,CAAA;QAEtD,sCAAiB,CAAC,MAAM,CAAC,IAAI,CAAC,6BAA6B,UAAU,CAAC,IAAI,mBAAmB,CAAC,CAAA;IAChG,CAAC;IAED,IAAI,aAAa;QACf,OAAO;YACL;gBACE,IAAI,EAAE,iBAAiB;gBACvB,IAAI,EAAE,YAAY;gBAClB,KAAK,EAAE,aAAa;gBACpB,QAAQ,EAAE;oBACR,SAAS,EAAE,eAAe;iBAC3B;aACF;YACD;gBACE,IAAI,EAAE,QAAQ;gBACd,IAAI,EAAE,oBAAoB;gBAC1B,KAAK,EAAE,qBAAqB;gBAC5B,QAAQ,EAAE;oBACR,OAAO,EAAE,CAAC,GAAG,EAAE,GAAG,CAAC;iBACpB;aACF;SACF,CAAA;IACH,CAAC;IAED,IAAI,YAAY;QACd,OAAO,CAAC,MAAM,CAAC,CAAA;IACjB,CAAC;CACF;AAvDD,sCAuDC;AAED,sCAAiB,CAAC,iBAAiB,CAAC,gBAAgB,EAAE,IAAI,aAAa,EAAE,CAAC,CAAA","sourcesContent":["import { Oauth2Client } from '@things-factory/oauth2-client'\nimport { getRepository } from '@things-factory/shell'\n\nimport { ConnectionManager } from '../connection-manager'\nimport { Connector } from '../types'\nimport { InputConnection } from '../../service/connection/connection-type'\n\nexport class HttpConnector implements Connector {\n async ready(connectionConfigs: InputConnection[]) {\n await Promise.all(connectionConfigs.map(this.connect.bind(this)))\n\n ConnectionManager.logger.info('http-connector connections are ready')\n }\n\n async connect(connection: InputConnection) {\n var { params } = connection\n params.rejectUnauthorized = (params.rejectUnauthorized || 'Y') === 'Y'\n\n if (params.authClient) {\n const oauth2Client: Oauth2Client = await getRepository(Oauth2Client).findOneBy({ id: params.authClient })\n var authHeaders = oauth2Client.getAuthHeaders()\n }\n\n ConnectionManager.addConnectionInstance(connection, {\n ...connection,\n authHeaders: authHeaders || {},\n params\n })\n\n ConnectionManager.logger.info(`http-connector connection(${connection.name}:${connection.endpoint}) is connected`)\n }\n\n async disconnect(connection: InputConnection) {\n ConnectionManager.removeConnectionInstance(connection)\n\n ConnectionManager.logger.info(`http-connector connection(${connection.name}) is disconnected`)\n }\n\n get parameterSpec() {\n return [\n {\n type: 'entity-selector',\n name: 'authClient',\n label: 'auth-client',\n property: {\n queryName: 'oauth2Clients'\n }\n },\n {\n type: 'select',\n name: 'rejectUnauthorized',\n label: 'reject-unauthorized',\n property: {\n options: ['Y', 'N']\n }\n }\n ]\n }\n\n get taskPrefixes() {\n return ['http']\n }\n}\n\nConnectionManager.registerConnector('http-connector', new HttpConnector())\n"]}
|
@@ -63,8 +63,8 @@ class OperatoConnector {
|
|
63
63
|
*/
|
64
64
|
const wsLink = new subscriptions_1.GraphQLWsLink((0, graphql_ws_1.createClient)({
|
65
65
|
url: uri.replace(/^http/, 'ws'),
|
66
|
-
keepAlive:
|
67
|
-
retryAttempts:
|
66
|
+
keepAlive: 10_000,
|
67
|
+
retryAttempts: 1_000_000,
|
68
68
|
shouldRetry: e => true,
|
69
69
|
webSocketImpl: ws_1.default,
|
70
70
|
connectionParams: {
|
@@ -79,7 +79,11 @@ class OperatoConnector {
|
|
79
79
|
return def.kind === 'OperationDefinition' && def.operation === 'subscription';
|
80
80
|
}, wsLink, (0, context_1.setContext)((_, { headers }) => {
|
81
81
|
return {
|
82
|
-
headers:
|
82
|
+
headers: {
|
83
|
+
...headers,
|
84
|
+
'x-things-factory-domain': domain,
|
85
|
+
authorization: authKey ? `Bearer ${authKey}` : ''
|
86
|
+
}
|
83
87
|
};
|
84
88
|
}).concat(httpLink));
|
85
89
|
const cache = new core_1.InMemoryCache({
|
@@ -114,9 +118,8 @@ class OperatoConnector {
|
|
114
118
|
});
|
115
119
|
const subscriptionObserver = subscription.subscribe({
|
116
120
|
next: async (data) => {
|
117
|
-
|
118
|
-
|
119
|
-
await this.runScenario(subscriptions, (_a = data === null || data === void 0 ? void 0 : data.data) === null || _a === void 0 ? void 0 : _a.data);
|
121
|
+
debug('received pubsub msg.:', data?.data);
|
122
|
+
await this.runScenario(subscriptions, data?.data?.data);
|
120
123
|
},
|
121
124
|
error: error => {
|
122
125
|
connection_manager_1.ConnectionManager.logger.error(`(${connection.name}:${connection.endpoint}) subscription error`, error);
|
@@ -146,13 +149,12 @@ class OperatoConnector {
|
|
146
149
|
connection_manager_1.ConnectionManager.logger.info(`operato-connector connection(${connection.name}) is disconnected`);
|
147
150
|
}
|
148
151
|
async runScenario(subscriptions, variables) {
|
149
|
-
var _a;
|
150
152
|
const { domain, user } = this.context;
|
151
153
|
const { tag } = variables;
|
152
154
|
if (!tag) {
|
153
155
|
throw new Error(`tag is invalid - ${tag}`);
|
154
156
|
}
|
155
|
-
const scenario =
|
157
|
+
const scenario = subscriptions.find(subscription => subscription.tag === tag)?.scenario;
|
156
158
|
if (!scenario) {
|
157
159
|
throw new Error(`scenario is not found - ${tag}`);
|
158
160
|
}
|